首页 > 解决方案 > How to match an even number of any character in a string?

问题描述

I have a string:

aaabbashasccddee

And I want to get matches of even number of consecutive same characters. For example, from the above string, I want these matches:

[bb],[cc],[dd],[ee]

I have tried this solution but it's not even close:

"^(..)*$

标签: c#regex

解决方案


幸运的是 .NET 正则表达式能够处理无限后视。使用以下正则表达式可以实现您所需要的:

((?>(?(2)(?=\2))(.)\2)+)(?<!\2\1)(?!\2)

在此处查看现场演示

正则表达式分解:

  • (开始捕获组 #1
    • (?>非捕获组的开始(原子)
      • (?(2)如果设置了捕获组 #2
        • (?=\2)下一个字符应该是它
      • )有条件的结束
      • (.)\2匹配并捕获一个字符并再次匹配(偶数)
    • )+尽可能重复,至少一次
  • )捕获组 #1 结束
  • (?<!\2\1)这是诀窍。后视告诉引擎,早于我们迄今为止匹配的前一个字符不应该是存储在捕获组 #2 中的相同字符
  • (?!\2)下一个字符不应与存储在捕获组 #2 中的字符相同

更新:

因此,您可以在 C# 中执行以下代码来获取字符串中的所有偶数序列字符,Regex而无需任何其他运算符(纯正则表达式)。

var allEvenSequences = Regex.Matches("aaabbashasccddee", @"((?>(?(2)(?=\2))(.)\2)+)(?<!\2\1)(?!\2)").Cast<Match>().ToList();

另外,如果您想制作,[bb],[cc],[dd],[ee]则可以加入该序列数组:

string strEvenSequences = string.Join(",", allEvenSequence.Select(x => $"[{x}]").ToArray());
//strEvenSequences will be [bb],[cc],[dd],[ee]

推荐阅读