Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing the first match with regex (C#)

Tags:

c#

regex

This is my first experience with C# and part of my limited experience with regular expressions and I'm having trouble capturing the first occurrence of a match in a particular expression. I believe the following example would make it more clear than words in describing what I want to do.

Match extractor = (new Regex(@".*\d(?<name>.*)\d.*")).Match("This hopefully will pick up 1Bob9error1 as a name");
        Console.WriteLine(extractor.Groups["name"]);

I would like to this expression to print "Bob" instead of "error".

I have a hunch it has something to do with the ? in front of the matching group, but I'm not exactly sure what operation the ? performs in this particular case. An explanation along with some help would be wonderful.

Thanks guys, you have no idea how much this site helps a beginning programmer like me.

like image 813
Chad Avatar asked Dec 01 '09 21:12

Chad


3 Answers

Your problem is greed. Regex greediness that is. Your .* at the start grabs all this "This hopefully will pick up 1Bob" . try this Regex instead:

\d(?<name>[^\d]+)\d
like image 172
nickytonline Avatar answered Sep 27 '22 20:09

nickytonline


Matches the preceding element zero or one time. It is equivalent to {0,1}. ? is a greedy quantifier whose non-greedy equivalent is ??.

Taken from here. Site includes a cheat-sheet for regular expressions, and looking at your expression I can't seem to figure out what may be wrong with it.

My assumption is that it might be matching the last occurrence of your expression.

like image 35
Anthony Forloney Avatar answered Sep 27 '22 19:09

Anthony Forloney


Each Group item has a Captures collection, you can access the first capture for a group using:

extractor.Groups["name"].Captures[0]
like image 41
Rory Avatar answered Sep 27 '22 18:09

Rory