How do you retrieve selected text using Regex in C#?
I am looking for C# code that is equivalent to this Perl code:
$indexVal = 0;
if($string =~ /Index: (\d*)/){$indexVal = $1;}
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
It indicates that the subpattern is a non-capture subpattern. That means whatever is matched in (?:\w+\s) , even though it's enclosed by () it won't appear in the list of matches, only (\w+) will.
To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.
- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"
int indexVal = 0;
Regex re = new Regex(@"Index: (\d*)")
Match m = re.Match(s)
if(m.Success)
indexVal = int.TryParse(m.Groups[1].toString());
I might have the group number wrong, but you should be able to figure it out from here.
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