Regex no two consecutive characters are the same

后端 未结 2 513
一个人的身影
一个人的身影 2020-12-21 23:04

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

For example

abcacb

相关标签:
2条回答
  • 2020-12-21 23:49

    ^(?!.*(.)\1)[abc]+$ works if you follow the original question exactly. However, this does not work/check multiple "words" of characters a/b/c, ie. "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".

    0 讨论(0)
  • 2020-12-21 23:49

    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 :)

    0 讨论(0)
提交回复
热议问题