Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex works in validator but not in C# [repeated capturing groups issue]

I have to parse the below string into three groups, Command, Target, Args.
Both Targets and Args are independently optional.

/ping@mybot arg1 arg2

I have created a regex with the valuable help of regexr.com, and I get the correct matches here.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

/(?<Command>[\w]*)+(?:@(?<Target>[\S]*)+)?(?<Args>[\s\S]*)?

enter image description here

However when I try and plug this into C#, I do not get any Matches, what could I have messed up here? I am @" escaping the string to avoid escaping issues:

var match = Regex.Match(cmd, @"/(?<Command>[\w]*)+(?:@(?<Target>[\S]*)+)?(?<Args>[\s\S]*)?");

Does C# require a different set of characters for it’s regex?

enter image description here

>Solution :

You need to convert repeated capturing groups into simple groups:

/(?<Command>\w+)(?:@(?<Target>\S+))?(?<Args>(?s).*)

See the regex demo.

Note I also replaced [\s\S] with . and added the (?s) inline modifier option to make the . after that modifier match any chars including line break chars. You may remove (?s) if you use RegexOptions.Singleline option in your code.

See the C# demo:

var pattern = @"/(?<Command>\w+)(?:@(?<Target>\S+))?(?<Args>(?s).*)";
var text = "/ping@mybot arg1 arg2";
var match = Regex.Match(text, pattern);
if (match.Success)
{
    Console.WriteLine(match.Groups["Command"].Value);
    Console.WriteLine(match.Groups["Target"].Value);
    Console.WriteLine(match.Groups["Args"].Value);
}

Output:

ping
mybot
 arg1 arg2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading