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


i can write regular expression match string contains 2 consecutive repeated characters:

/(\w)\1/ 

how do complement of that? want match strings don't have 2 consecutive repeated characters. i've tried variations of following without success:

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

i don't want language/platform specific way take negation of regular expression. want straightforward way this.

the below regex match strings don't have repeated characters.

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

(?!.*(\w)\1) negative lookahead asserts string going matched won't contain repeated characters. .*(\w)\1 match string has repeated characters @ middle or @ start or @ end. ^(?!.*(\w)\1) matches starting boundaries except 1 has repeated characters. , following .* matches characters exists on particular line. note this matches empty strings also. if don't want match empty lines change .* @ last .+

note ^(?!(\w)\1) checks repeated characters @ start of string or line.

lookahead , lookbehind, collectively called "lookaround", zero-length assertions start , end of line. not consume characters in string, assert whether match possible or not. lookaround allows create regular expressions impossible create without them, or longwinded without them.


Comments

Popular posts from this blog

java - Could not locate OpenAL library -

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

sorting - opencl Bitonic sort with 64 bits keys -