[英]How to match an odd number of any character in a string?
我正在寻找一个纯粹的正则表达式解决方案来获得由相似字符组成的奇数长度子串。
例如,我的字符串:
hjasaaasjasjbbbbbashjasccccccc
因此,产生的匹配应该是:
[aaa],[bbbbb],[ccccccc]
到目前为止,我尝试过:
(?<!\1\1)*(?<!\1)(.)(\1\1)*(?:\1\1)*(?!\1)
但它不起作用。
对于匹配任意字符的奇数的正则表达式解决方案( 不包括单字符匹配):
(.)(?<!\1\1)\1(?:\1\1)*\1(?!\1)
或者更短版本归功于Wiktor :
(.)(?<!\1\1)(?:\1\1)+(?!\1)
演示 。
分解:
(.) # First capturing group - matches any character.
(?<!\1\1) # Negative lookbehind - ensures the matched char isn't preceded by the same char.
(?:\1\1) # A non-capturing group that matches two occurrences of
# the same char (at least 3 in total).
+ # Matches between one and unlimited times of the previous group.
(?!\1) # Negative lookahead to make sure no extra occurrence of the char follows.
C#中的演示:
string input = "hjasaaasjasjbbbbbashjasccccccc";
string pattern = @"(.)(?<!\1\1)(?:\1\1)+(?!\1)";
var matches = Regex.Matches(input, pattern);
foreach (Match m in matches)
Console.WriteLine(m.Value);
输出:
aaa
bbbbb
ccccccc
如果您想要一个与奇数个任意字符匹配的解决方案( 包括一个字符匹配):
(.)(?<!\1\1)(?:\1\1)*(?!\1)
演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.