Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you retrieve selected text using Regex in C#?

Tags:

c#

regex

perl

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;}
like image 387
Eldila Avatar asked Aug 12 '08 23:08

Eldila


People also ask

How do I find a character in a string in regex?

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).

What is ?: In regex?

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.

How do I capture a number in regex?

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.

Why * is used in regex?

- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"


1 Answers

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.

like image 71
Patrick Avatar answered Nov 15 '22 16:11

Patrick