Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex in C# acting weird

Tags:

c#

regex

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: enter image description here

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.

like image 260
Steven Bonell Avatar asked Dec 16 '22 06:12

Steven Bonell


2 Answers

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.

like image 164
Jon Skeet Avatar answered Dec 18 '22 10:12

Jon Skeet


You are looking into _groups field, but it's not exactly what is returned as Groups property:

enter image description here

Change your code to use Groups[1] and Groups[2]:

string nick = match2.Groups[2].Value;
string name = match2.Groups[1].Value;
like image 31
MarcinJuraszek Avatar answered Dec 18 '22 12:12

MarcinJuraszek