I've encountered a problem while working with regex in C#. Namely, the debugger shows correct(IMO) results but when I try to print the results in my application, they are different(and wrong). Code below:
Match match2 = Regex.Match("048 A Dream Within A Dream (satur) (123|433) K48", "(.*)(\\((.)*?\\))\\s\\((.)*?\\)\\s.*");
string nick = match2.Groups[1].Value;
string name = match2.Groups[0].Value;
Console.WriteLine("nick - '{0}', name - '{1}'", nick, name);
Expected results show up in the debugger, as in following screenshot:
Console shows different(wrong) results:
nick - '048 A Dream Within A Dream ', name - '048 A Dream Within A Dream (satur) (123|433) K48'
How do I fix it? I want the results to be shown exactly as in debugger.
You're missing the fact that Groups[0]
is always meant to represent the whole match. The first capturing group is in Groups[1]
. You want:
string nick = match2.Groups[2].Value;
string name = match2.Groups[1].Value;
The reason it's showing what you expected in the debugger is that you're looking at the implementation detail of a field within GroupCollection
; when it's asked for a group by number, it returns the match if the requested number is 0, or offsets the number by 1 otherwise.
From the documentation for GroupCollection
:
If the match is successful, the first element in the collection contains the Group object that corresponds to the entire match. Each subsequent element represents a captured group, if the regular expression includes capturing groups.
You are looking into _groups
field, but it's not exactly what is returned as Groups
property:
Change your code to use Groups[1]
and Groups[2]
:
string nick = match2.Groups[2].Value;
string name = match2.Groups[1].Value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With