C# “我该怎么做?”;削减;用正则表达式写出字符串的一部分?

C# “我该怎么做?”;削减;用正则表达式写出字符串的一部分?,c#,regex,C#,Regex,我需要在C#中剪切并保存/使用字符串的一部分。我认为最好的方法是使用正则表达式。我的字符串如下所示: “从1更改为10” 我需要一种方法来删掉这两个数字,并在其他地方使用它们。做这件事的好方法是什么?在正则表达式中,将要记录的字段放在括号中,然后使用Match.Captures属性提取匹配的字段 有一个C#示例。使用命名的捕获组 Regex r = new Regex("*(?<FirstNumber>[0-9]{1,2})*(?<SecondNumber>[0-9]{1

我需要在C#中剪切并保存/使用字符串的一部分。我认为最好的方法是使用正则表达式。我的字符串如下所示:

“从1更改为10”


我需要一种方法来删掉这两个数字,并在其他地方使用它们。做这件事的好方法是什么?

在正则表达式中,将要记录的字段放在括号中,然后使用
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;
 }
Regex r=newregex(“*([0-9]{1,2})*([0-9]{1,2})*”);
字符串输入=“从1更改为10”;
字符串firstNumber=“”;
字符串secondNumber=“”;
MatchCollection joinMatches=regex.Matches(输入);
foreach(joinMatches中的匹配m)
{
firstNumber=m.Groups[“firstNumber”].值;
secondNumber=m.Groups[“secondNumber”].值;
}
为了帮助您,它有一个导出到C#选项


免责声明:正则表达式可能不正确(我的expresso副本已过期:D)

仅匹配字符串“从x更改为y”:


作为练习检查左侧时出错

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

下面是一段代码片段,它几乎实现了我想要的功能:

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)));
    }
}
使用System.Text.regular表达式;
string text=“从1更改为10”;
字符串模式=@“\b(?\d+)\b”;
正则表达式r=新正则表达式(模式);
MatchCollection mc=r.Matches(文本);
foreach(在mc中匹配m){
CaptureCollection cc=m.Groups[“digit”]。捕获;
foreach(在cc中捕获c){
Console.WriteLine((Convert.ToInt32(c.Value));
}
}

r.Match应为大写字母“M”。此示例在测试运行时为我提供了System.InvalidCastException:无法将System.Text.RegularExpressions.Match转换为System.IConvertible此操作失败,因为您查看的CaptureCollection不正确。此代码将匹配三个组(整个文本、第一个父项和第二个父项),每个组有一个捕获。因此,本例中的代码对整个文本和超出范围的项使用匹配。此外,当从捕获对象转换时,您应该使用Value属性。
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)));
    }
}