문제

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";
...
도움이 되었습니까?

해결책

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top