【问题标题】:How do I "cut" out part of a string with a regex?如何使用正则表达式“剪切”字符串的一部分?
【发布时间】:2008-11-13 13:53:41
【问题描述】:

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

"changed from 1 to 10"

我需要一种方法来删除这两个数字并在其他地方使用它们。有什么好的方法可以做到这一点?

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    错误检查留作练习...

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

    【讨论】:

      【解决方案2】:

      只匹配字符串“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
      }
      

      【讨论】:

      • r.Match 应该是大写的“M”。这个例子在我测试运行时给了我一个 System.InvalidCastException:Can't convert System.Text.RegularExpressions.Match to System.Iconvertible
      • 这会失败,因为您正在查看不正确的 CaptureCollection。此代码将匹配三个组(整个文本、第一个 parenteses 和第二个 parenteses),每个组都有一个 Capture。所以这个例子中的代码使用了对整个文本和一个超出范围的项目的匹配。
      • 另外,从 Capture 对象转换时,您应该使用 Value-property。
      【解决方案3】:

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

      有一个 C# 示例here

      【讨论】:

        【解决方案4】:

        使用命名的捕获组。

        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# 的选项。

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

        【讨论】:

          【解决方案5】:

          这是一个代码 sn-p,它几乎完成了我想要的:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-07-08
            • 2023-03-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-01-15
            相关资源
            最近更新 更多