tags:

views:

1228

answers:

5

I need to cut out and save/use part of a string in C#. I figure the best way to do this is by using Regex. My string looks like this:

"changed from 1 to 10".

I need a way to cut out the two numbers and use them elsewhere. What's a good way to do this?

+2  A: 

In your regex put the fields you want to record in parentheses, and then use the Match.Captures property to extract the matched fields.

There's a C# example here.

Alnitak
+1  A: 

Use named capture groups.

Regex r = new Regex("*(?<FirstNumber>[0-9]{1,2})*(?<SecondNumber>[0-9]{1,2})*");
 string input = "changed from 1 to 10";
 string firstNumber = "";
 string secondNumber = "";

 MatchCollection joinMatches = regex.Matches(input);

 foreach (Match m in joinMatches)
 {
  firstNumber= m.Groups["FirstNumber"].Value;
  secondNumber= m.Groups["SecondNumber"].Value;
 }

Get Expresson to help you out, it has an export to C# option.

DISCLAIMER: Regex is probably not right (my copy of expresso expired :D)

Rob Stevenson-Leggett
+4  A: 

Matching only exactly the string "changed from x to y":

string pattern = @"^changed from ([0-9]+) to ([0-9]+)$";
Regex r = new Regex(pattern);
Match m = r.match(text);
if (m.Success) {
   Group g = m.Groups[0];
   CaptureCollection cc = g.Captures;

   int from = Convert.ToInt32(cc[0]);
   int to = Convert.ToInt32(cc[1]);

   // Do stuff
} else {
   // Error, regex did not match
}
phihag
r.Match should be uppercase 'M'. This example gives me a System.InvalidCastException when I testrun it:Can't convert System.Text.RegularExpressions.Match to System.Iconvertible
Cros
This fails because you are looking at the CaptureCollection which is incorrect. This code will match three groups (the entire text, the first parenteses and the second parenteses) with one Capture each. So the code in this example uses the match against the entire text and an out of range item.
Cros
Also, when converting from a Capture object you should use the Value-property.
Cros
+9  A: 

Error checking left as an exercise...

        Regex regex = new Regex( @"\d+" );
        MatchCollection matches = regex.Matches( "changed from 1 to 10" );
        int num1 = int.Parse( matches[0].Value );
        int num2 = int.Parse( matches[1].Value );
tvanfosson
A: 

Here is a code snippet that does almost what I wanted:

using System.Text.RegularExpressions;

string text = "changed from 1 to 10";
string pattern = @"\b(?<digit>\d+)\b";
Regex r = new Regex(pattern);
MatchCollection mc = r.Matches(text);
foreach (Match m in mc) {
    CaptureCollection cc = m.Groups["digit"].Captures;
    foreach (Capture c in cc){
     Console.WriteLine((Convert.ToInt32(c.Value)));
    }
}
Cros