Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何匹配字符串中任意字符的偶数?_C#_Regex - Fatal编程技术网

C# 如何匹配字符串中任意字符的偶数?

C# 如何匹配字符串中任意字符的偶数?,c#,regex,C#,Regex,我有一个字符串: aaabbashasccddee 我想得到偶数个连续相同字符的匹配。例如,从上面的字符串中,我需要以下匹配项: [bb],[cc],[dd],[ee] 我已经尝试过这个解决方案,但还没有接近: "^(..)*$ 请提供任何帮助幸运的是.NET正则表达式能够处理无限的lookbehind。使用以下正则表达式可以实现您所需的功能: ((?>(?(2)(?=\2))(.)\2)+)(?<!\2\1)(?!\2) 另外,如果您想制作[bb]、[cc]、[dd]、[e

我有一个字符串:

aaabbashasccddee
我想得到偶数个连续相同字符的匹配。例如,从上面的字符串中,我需要以下匹配项:

[bb],[cc],[dd],[ee]
我已经尝试过这个解决方案,但还没有接近:

"^(..)*$

请提供任何帮助

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

((?>(?(2)(?=\2))(.)\2)+)(?<!\2\1)(?!\2)
另外,如果您想制作
[bb]、[cc]、[dd]、[ee]
,则可以加入该序列数组:

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

另一种可能的不涉及条件的仅限正则表达式的解决方案:

(.)(?<!\1\1)\1(?:\1\1)*(?!\1)

你有这么多这样的帖子。“你到底想实现什么?”约翰:为什么,这有什么问题吗?在我看来,你只是在零零碎碎地尝试建造一些东西,而当你请求帮助时,最好让我们了解更大的情况。也许有更好的方法来做你想做的事。这是黄金。我喜欢这个主意+1@revo非常感谢:-)在问题发布几分钟后,我实际上正在做这件事,但一旦问题得到了一个有效解决方案的答案(现在被删除),我就放弃了它。然后,当OP要求提供一个只有正则表达式的解决方案时,我看到了你的答案(这很好,顺便说一句),我说“好吧,让我也发布我的版本”:-D@AhmedAbdelhameed
(?>…)
(?@Alex
(?>…)
之间的区别是什么(?@Alex负lookback表示下一个字符前面不能有lookback中的内容。请阅读我提供的文章以了解更多内容。这解释了Lookaheads、Lookbehinds和原子组。
(.)(?<!\1\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          # Match another one of the character in the 1st group (at least two in total).
(?:\1\1)    # A non-capturing group that matches two occurrences of the same char.
*           # Matches between zero and unlimited times of the previous group.
(?!\1)      # Negative lookahead to make sure no extra occurrence of the char follows.
string input = "aaabbashasccddee";
string pattern = @"(.)(?<!\1\1)\1(?:\1\1)*(?!\1)";
var matches = Regex.Matches(input, pattern);
foreach (Match m in matches)
    Console.WriteLine(m.Value);