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

大城市里の小女人 提交于 2019-12-17 20:28:05

问题


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 complement of that? I want to match strings that don't have 2 consecutive repeated characters. I've tried variations of the following without success:

/(\w)[^\1]/ ;doesn't work as hoped
/(?!(\w)\1)/ ;looks ahead, but some portion of the string will match
/(\w)(?!\1)/ ;again, some portion of the string will match

I don't want any language/platform specific way to take the negation of a regular expression. I want the straightforward way to do this.


回答1:


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.



来源:https://stackoverflow.com/questions/29179164/regular-expression-pattern-to-match-string-without-any-2-consecutive-repeated-ch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!