如何使用正则表达式“剪切”字符串的一部分?

6
我需要在C#中截取并保存/使用字符串的一部分。我认为最好的方法是使用正则表达式。我的字符串看起来像这样:"changed from 1 to 10"。我需要一种方法来截取这两个数字并在其他地方使用它们。有什么好的方法可以做到这一点?
5个回答

11

错误检查留作练习...

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

4

仅匹配完全相同的字符串"从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
}

r.Match 应该大写为 'M'。当我测试运行此示例时,它会给我一个 System.InvalidCastException:无法将 System.Text.RegularExpressions.Match 转换为 System.Iconvertible。 - Cros
这个失败是因为你查看了错误的CaptureCollection。这段代码将匹配三个组(整个文本、第一个括号和第二个括号),每个组都有一个Capture。所以在这个例子中,代码使用整个文本进行匹配,并且超出范围。 - Cros
此外,当从 Capture 对象进行转换时,应使用 Value 属性。 - Cros

2

在你的正则表达式中,将你想要记录的字段放在括号中,然后使用Match.Captures属性提取匹配的字段。

这里有一个C#示例


1
使用命名捕获组。
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)


0

这里有一段代码片段,它实现了我想要的几乎所有功能:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接