Question

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;}
Was it helpful?

Solution

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.

OTHER TIPS

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

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;

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;
int indexVal = 0;
Regex re = new Regex.Match(s, @"(<?=Index: )(\d*)");

if(re.Success)
{
  indexVal = Convert.ToInt32(re.Value);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top