简体   繁体   中英

How do I “cut” out part of a string with a regex?

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?

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

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
}

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 .

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)

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)));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM