USER1287
USER1287

Reputation: 53

Regex or Linq to capture the key and value pair in c#

I have a string like below

Loop="start:yes " while=" end" do=" yes "

expected string
Loop="start:yes" while="end" do="Yes"

I tried to capture the key and value pair(ex. Loop="start:yes ") and remove the white space in each pair and then concatenate whole string as expected string above

        //string rx = "([\\w+\\s]*\\=?[\\s]*\\\"[\\w+\\s]*\\\")";

        string rx = ".+?\\=?[\\s]*\\\".+?\\\"";

        Console.WriteLine(rx);
        Match m = Regex.Match(tempString, rx, RegexOptions.IgnoreCase);

        if (m.Success)
        {

            Console.WriteLine(m.Groups[1].Value);    
            Console.WriteLine(m.Groups[2].Value);   
            Console.WriteLine(m.Groups[3].Value);   
            Console.WriteLine(m.Groups[4].Value);

        }

Tried above code but am unable to capture any pair in the string

Upvotes: 3

Views: 391

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626699

You can pass a callback method to the Regex.Replace, and inside that method, populate an object of Dictionary<string, string>.

You can use the following regex to grab the keys and values:

(?<key>\w+)="\s*(?<val>.*?)\s*"

The regex matches:

  • (?<key>\w+) - matches and stores in a capture group nameskey 1 or more alphanumeric symbols or underscore
  • =" - a literal ="
  • \s* - 0 or more whitespace
  • (?<val>.*?) - matches and captures into group names val any number of any characters but a newline as few as possible before the closest...
  • \s*" - 0 or more whitespace symbols followed by a ".

Here is the C# demo:

private Dictionary<string, string> dct = new Dictionary<string, string>();
private string callbck(Match m)
{
    dct.Add(m.Groups["key"].Value, m.Groups["val"].Value);
    return string.Format("{0}=\"{1}\"", m.Groups["key"].Value, m.Groups["val"].Value);
}

And this is the main code:

var s = "Loop=\"start:yes \" while=\" end\" do=\" yes \"";
var res = Regex.Replace(s, @"(?<key>\w+)=""\s*(?<val>.*?)\s*""",  callbck);

Result: Loop="start:yes" while="end" do="yes",

enter image description here

Upvotes: 1

Related Questions