Home > Software engineering >  Regex works in validator but not in C# [repeated capturing groups issue]
Regex works in validator but not in C# [repeated capturing groups issue]

Time:08-27

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.

/(?<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

CodePudding user response:

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
  • Related