Capturing first match with regex (C #)

This is my first experience with C # and part of my limited experience with regular expressions, and I had trouble writing the first match in a specific expression. I believe that the following example will make it more understandable than the words in the description of 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 this expression to print “Bob” instead of “error”.

Do I have a suspicion that this has anything to do with this? in front of the appropriate group, but I'm not quite sure what operation? performs in this particular case. An explanation along with some help would be wonderful.

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

+5
source share
4 answers

Your problem is greed. Regex greed that is. Your. * In the beginning, all of this is enough, "This, I hope, will raise 1Bob." try this regex:

\d(?<name>[^\d]+)\d
+7
source

Matches the previous item zero or once. is it equivalent to {0,1}.? it is a greedy quantifier whose unwanted equivalent is ??.

Taken from here . The site includes a cheat sheet for regular expressions, and looking at your expression, I can’t understand what could be a mistake with it.

My guess is that it may correspond to the last occurrence of your expression.

+3
source

Captures, , :

extractor.Groups["name"].Captures[0]
+2

Bracketing * characters around your expression causes problems. Remember that you do not need a regular expression that matches the entire string — you want it to match only a specific pattern when it appears. The following code works:

Regex pattern = new Regex(@"\d(?<name>.*?)\d");
MatchCollection matches = pattern.Matches("This hopefully will pick up 1Bob9error1 as a name");
Console.WriteLine(matches[0].Groups["name"]);
+2
source

All Articles