2

假设我有以下字符串

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";
...
4

1 回答 1

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;
}
于 2010-12-25T08:00:31.083 回答