[英]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.