简体   繁体   English

正则表达式没有两个连续的字符是相同的

[英]Regex no two consecutive characters are the same

How do I write a regular expression where x is a string whose characters are either a, b, c but no two consecutive characters are the same如何编写正则表达式,其中 x 是一个字符串,其字符为 a、b、c 但没有两个连续字符相同

For example例如

abcacb is true abcacb 是真的

acbaac is false acbaac 是假的

^(?!.*(.)\\1)[abc]+$ works if you follow the original question exactly. 如果您完全按照原始问题, ^(?!.*(.)\\1)[abc]+$有效。 However, this does not work/check multiple "words" of characters a/b/c, ie. 然而,这不起作用 /检查字符的多个“改为” A / B / C,即。 "abc cba". “abc cba”。

The way it works is it asserts that any character is not followed by itself by utilizing a capture group inside a lookahead and that the entire string consists only of characters "a", "b", or "c". 它的工作方式是断言任何字符都不会通过利用前瞻中的捕获组来跟随它,并且整个字符串只包含字符“a”,“b”或“c”。

Since the number of chars is limited, you can get away without a back reference in the look ahead: 由于字符数量有限,您可以在前面没有后退参考的情况下离开:

^(?!.*(aa|bb|cc)[abc]*$

But I like tenub's answer better :) 但我更喜欢tenub的答案:)

Other solutions apart from the two mentioned already:除了已经提到的两个解决方案之外的其他解决方案:

using negative lookbehind: ^((a|b|c)(?<!(aa|bb|cc)))*$使用负向后视: ^((a|b|c)(?<!(aa|bb|cc)))*$

using negative lookahead: ^((?!(aa|bb|cc))(a|b|c))*$使用负前瞻: ^((?!(aa|bb|cc))(a|b|c))*$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM