tags:

views:

684

answers:

4

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;}
+7  A: 
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.

Patrick
+1  A: 

You'll want to utilize the matched groups, so something like...

Regex MagicRegex = new Regex(RegexExpressionString);
Match RegexMatch;
string CapturedResults;

RegexMatch = MagicRegex.Match(SourceDataString);
CapturedResults = RegexMatch.Groups[1].Value;
Dillie-O
+5  A: 

I think Patrick nailed this one -- my only suggestion is to remember that named regex groups exist, too, so you don't have to use array index numbers.

Regex.Match(s, @"Index (?<num>\d*)").Groups["num"].Value

I find the regex is a bit more readable this way as well, though opinions vary...

Jeff Atwood
+1  A: 

That would be

int indexVal = 0;
Regex re = new Regex(@"Index: (\d*)");
Match m = re.Match(s);
if (m.Success) indexVal = m.Groups[1].Index;

You can also name you group (here I've also skipped compilation of the regexp)

int indexVal = 0;
Match m2 = Regex.Match(s, @"Index: (?<myIndex>\d*)");
if (m2.Success) indexVal = m2.Groups["myIndex"].Index;
Andreas H.R. Nilsson