【问题标题】:How to capture matches and mismatches in c# regex?如何在 c# 正则表达式中捕获匹配和不匹配?
【发布时间】:2012-07-21 19:58:03
【问题描述】:

我有一些格式的消息,例如:

"?I?Message message message\r\n"

现在我想使用命名组通过正则表达式捕获此消息:

(?<Message>\?(?<Type>\S)\?(?<Text>[\S\s]+(\r\n)+))

但我也想拥有与此消息格式不匹配的所有字符串。例如:

"Some data?I?Message message\r\nAnother part of data\n"

会给我 3 场比赛:

  • “一些数据”
  • ?I?消息消息\r\n
  • "另一部分数据\n"

我可以检查消息组是否将 Success 字段设置为 true,以检查是否出现任何上述格式的消息。否则我会得到一些“原始数据”。 是否可以使用正则表达式和匹配来做这样的事情?

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    来自Regex.Match 的结果对象是Match 类型。它的Success 属性显示正则表达式作为一个整体是否匹配。

    但是还有一个Groups 属性,您可以使用它来查看个人(无论是否命名)捕获组。如果命名捕获未能匹配,则该组的 Success 属性将为 false。

    所以

    var m = Regex.Match("Fubar", "(?<x>Z)?.*");
    

    然后

    m.Success
    

    是真的,但是

    m.Groups['Z'].Success
    

    是假的。

    使用Regex.Matches,正则表达式可以匹配多次,每次匹配将是返回的MatchCollection 中的一个Match 对象。 但是正则表达式默认会跳过不匹配的输入部分,因此:

    Regex.Matches("ZaZ", "Z")
    

    将返回两个匹配项的集合,但“a”不返回任何内容。您可以使用\G 锚点强制下一场比赛在上一场比赛之后立即开始。

    【讨论】:

      【解决方案2】:

      这是一种方法:

      var str = "Some data?I?Message message\r\nAnother part of data\n";
      var unmatchedCharIndices = Enumerable.Range(0, str.Length);
      foreach (Match match in Regex.Matches(str, @"(?<Message>\?(?<Type>\S)\?(?<Text>[\S\s]+(\r\n)+))"))
      {
          unmatchedCharIndices = unmatchedCharIndices.Except(Enumerable.Range(match.Index, match.Length));
          //do other stuff with match
      }
      var unmatchedStrings = unmatchedCharIndices
                  .Select((n, i) => new { n, i })
                  .GroupBy(x => x.n - x.i) //this line will group consecutive nums in the seq
                  .Select(x => str.Substring(x.First().n, x.Count()));
      foreach (var unmatchedString in unmatchedStrings)
      {
          //do something with non-match text
      }
      

      unmatchedStrings 代码感谢Getting last x consecutive items with LINQ 开始)

      【讨论】:

      • 好的,这适用于我的示例输入数据,但不适用于本示例:“Some data?I?Message message\r\nAnother part of data\n”
      • 再次修改,我找到了一些代码将不匹配的字符索引分组到它们的字符串中。
      【解决方案3】:

      To match mismatches

      string toSearchString = "your string here";
      
      Match match = new Regex("*some pattern here*").Match(toSearchString );
      
      string unmatchedString = toSearchString.Replace(match.Value,"");
      

      所以现在你有了 Unmatched String。你可以喝咖啡!!

      【讨论】:

        猜你喜欢
        • 2021-12-24
        • 2015-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多