2

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

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.