简体   繁体   中英

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);

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.

在此处输入图片说明

RegEx

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

RegEx Circuit

You can also visualize your expressions in jex.im :

在此处输入图片说明

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM