将两个正则表达式组组合成一个键/值对对象?

发布于 2024-10-09 07:10:33 字数 387 浏览 0 评论 0原文

假设我有以下字符串

Type="Category" Position="Top" Child="3" ABC="XYZ"....

和 2 个正则表达式组:键和值

Key: "Type", "Position", "Child",...
Value: "Category", "Top", "3",...

我们如何将这 2 个捕获组组合成像 Hashtable 这样的键/值对对象?

Dictionary["Type"] = "Category";
Dictionary["Position"] = "Top";
Dictionary["Child"] = "3";
...

Let's say that I have the following string

Type="Category" Position="Top" Child="3" ABC="XYZ"....

And 2 regex groups: Key and Value

Key: "Type", "Position", "Child",...
Value: "Category", "Top", "3",...

How can we combine these 2 captured groups into key/value pair object like Hashtable?

Dictionary["Type"] = "Category";
Dictionary["Position"] = "Top";
Dictionary["Child"] = "3";
...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤芳又自赏 2024-10-16 07:10:34

我的建议:

System.Collections.Generic.Dictionary<string, string> hashTable = new System.Collections.Generic.Dictionary<string, string>();

string myString = "Type=\"Category\" Position=\"Top\" Child=\"3\"";
string pattern = @"([A-Za-z0-9]+)(\s*)(=)(\s*)("")([^""]*)("")";

System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(myString, pattern);
foreach (System.Text.RegularExpressions.Match m in matches)
{
    string key = m.Groups[1].Value;    // ([A-Za-z0-9]+)
    string value = m.Groups[6].Value;    // ([^""]*)

    hashTable[key] = value;
}

My suggestion:

System.Collections.Generic.Dictionary<string, string> hashTable = new System.Collections.Generic.Dictionary<string, string>();

string myString = "Type=\"Category\" Position=\"Top\" Child=\"3\"";
string pattern = @"([A-Za-z0-9]+)(\s*)(=)(\s*)("")([^""]*)("")";

System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(myString, pattern);
foreach (System.Text.RegularExpressions.Match m in matches)
{
    string key = m.Groups[1].Value;    // ([A-Za-z0-9]+)
    string value = m.Groups[6].Value;    // ([^""]*)

    hashTable[key] = value;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文