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

时间:2010-12-25 07:25:34

标签: c# regex join regex-group captured-variable

假设我有以下字符串

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

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

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

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

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

1 个答案:

答案 0 :(得分:1)

我的建议:

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;
}