Reputation: 271
I have a string like this:
So basically i need a regular expression to get those 4 numeric values after the _ delimiter. I'm sure it's super simply but Regex looks like a foreign language to me!
Upvotes: 0
Views: 4826
Reputation: 29562
That would be this regular expression:
_([0-9]+)
(Capture group 1 holds the number.)
Or if your engine supports lookbehinds (which as far as I remember is not the case for C#):
(?<=_)[0-9]+
(Capture group 0 holds the number.)
The (...)
denotes a catch group. In your match object you can then either access them by their index via yourMatch.Groups[index].Value
or if you named your catch groups via (?<name>...)
by their name like yourMatch.Groups[name].Value
. The value will then hold whatever was matched by that particular group's sub-expression (in your case the 4-digit number).
Also if you only want the regex to match if those are exactly 4 numeric characters,
then replace the +
with {4}\b
Edit: As Alan Moore correctly pointed out those are called "capture group", not "catch group". I need more sleep.
Upvotes: 4
Reputation: 18125
Regex: _(?<number>[0-9]+)
var match = new Regex("_(?<number>[0-9]+)").Match("blah blah blah_0123");
if(match.Success)
{
var value = match.Groups["number"].Value;
var number = Int.Parse(value);
Console.WriteLine(value); // this will write "0123"
Console.WriteLine(number); // this will write "123"
}
Upvotes: 2