Search code examples
c#regexjoinregex-groupcaptured-variable

Combine two regex groups into a key/value pair object?


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

Solution

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