c# - 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:
"^(..)*$
解决方案
幸运的是 .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]
推荐阅读
- c# - 在 ASP.NET Core 上配置 DefaultScheme 和 DefaultChallengeScheme 有什么意义?
- arrays - 子数组的总和乘以子数组的最后一个元素
- android - 将动态子视图垂直添加到 ConstraintLayout
- android - 在键盘显示状态屏幕不可滚动
- android - 是否可以在 AppWidgetProvider 中使用 LiveData
- unit-testing - Groovy Spock BlockingVariable 从未发布
- image - 我无法删除设置默认博主的图像之间的空白
- c++ - 如何使用 CreateFile 在 Windows 中以 UnBuffered 模式追加文件
- android - 如何将数据从服务器/管理器传递到 viewmodel RxJava Android
- java - Java feign 客户端拒绝连接