Regular expression pattern to match string without any 2 consecutive repeated characters

后端 未结 1 965
暗喜
暗喜 2020-12-11 11:20

I can very easily write a regular expression to match a string that contains 2 consecutive repeated characters:

/(\\w)\\1/

How do I do the

相关标签:
1条回答
  • 2020-12-11 11:48

    The below regex would match the strings which don't have any repeated characters.

    ^(?!.*(\w)\1).*
    

    (?!.*(\w)\1) negative lookahead which asserts that the string going to be matched won't contain any repeated characters. .*(\w)\1 will match the string which has repeated characters at the middle or at the start or at the end. ^(?!.*(\w)\1) matches all the starting boundaries except the one which has repeated characters. And the following .* matches all the characters exists on that particular line. Note this this matches empty strings also. If you don't want to match empty lines then change .* at the last to .+

    Note that ^(?!(\w)\1) checks for the repeated characters only at the start of a string or line.

    Lookahead and lookbehind, collectively called "lookaround", are zero-length assertions just like the start and end of line. They do not consume characters in the string, but only assert whether a match is possible or not. Lookaround allows you to create regular expressions that are impossible to create without them, or that would get very longwinded without them.

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