簡體   English   中英

如何用正則表達式“剪掉”部分字符串?

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

我需要在C#中剪切並保存/使用部分字符串。 我認為最好的方法是使用Regex。 我的字符串看起來像這樣:

"changed from 1 to 10"

我需要一種方法來刪除這兩個數字並在其他地方使用它們。 這樣做的好方法是什么?

錯誤檢查左側作為練習...

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

僅匹配字符串“從x更改為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
}

在正則表達式中,將要記錄的字段放在括號中,然后使用Match.Captures屬性提取匹配的字段。

有一個C#示例在這里

使用命名捕獲組。

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

Expresson幫助你,它有一個導出到C#選項。

免責聲明:正則表達式可能不對(我的expresso副本已過期:D)

這是一個幾乎完全符合我要求的代碼片段:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM