Search code examples
c#regexregex-lookaroundsregex-groupregex-greedy

RegEx Capturing Groups in C#


I'm trying to parse a file's contents using regex, but the patter I came up with doesn't seem to work.

The regex I am trying to use is

string regex = @"^(?<key>\w+?)\s*?:\s*?{(?<value>[\s\S]+?)}$";

and the text i am trying to parse it against is

string text = @"key:{value}
key:{valu{0}e}
key:{valu
{0}e}
key:{val-u{0}e}
key:{val__[!]
-u{0}{1}e}";

However, it returns 0 results

MatchCollection matches = Regex.Matches(text, regex, RegexOptions.Multiline);

I have tried testing this regex on RegExr, which worked as expected.
I am unsure why this doesn't work when trying it in C#.

MCVE:

string regex = @"^(?<key>\w+?)\s*?:\s*?{(?<value>[\s\S]+?)}$";
string text = @"key:{value}
key:{valu{0}e}
key:{valu
{0}e}
key:{val-u{0}e}
key:{val__[!]
-u{0}{1}e}";
MatchCollection matches = Regex.Matches(text, regex, RegexOptions.Multiline);
Console.WriteLine(matches.Count);

Solution

  • One way we might like to try is to test that if our expression would be working in another language.

    Also, we might want to simplify our expression:

    ^(.*?)([\s:]+)?{([\s\S].*)?.$
    

    where we have three capturing groups. The first and third ones are our desired key and values.

    enter image description here

    RegEx

    You can modify/simplify/change your expressions in regex101.com.

    RegEx Circuit

    You can also visualize your expressions in jex.im:

    enter image description here

    JavaScript Demo

    const regex = /^(.*?)([\s:]+)?{([\s\S].*)?.$/gm;
    const str = `key:{value}
    key:{valu{0}e}
    key:{valu
    {0}e}
    key:   {val-u{0}e}
    key:  {val__[!]
    -u{0}{1}e}`;
    const subst = `$1,$3`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, subst);
    
    console.log('Substitution result: ', result);

    C# Test

    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
        public static void Main()
        {
            string pattern = @"^(.*?)([\s:]+)?{([\s\S].*)?.$";
            string substitution = @"$1,$3";
            string input = @"key:{value}
    key:{valu{0}e}
    key:{valu
    {0}e}
    key:   {val-u{0}e}
    key:  {val__[!]
    -u{0}{1}e}";
            RegexOptions options = RegexOptions.Multiline;
    
            Regex regex = new Regex(pattern, options);
            string result = regex.Replace(input, substitution);
        }
    }
    

    Original RegEx Test

    const regex = /^(?<key>\w+?)\s*?:\s*?{(?<value>[\s\S]+?)}$/gm;
    const str = `key:{value}
    key:{valu{0}e}
    key:{valu
    {0}e}
    key:   {val-u{0}e}
    key:  {val__[!]
    -u{0}{1}e}`;
    const subst = `$1,$2`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, subst);
    
    console.log('Substitution result: ', result);

    References: