Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 571
at. Avatar asked Jun 28 '26 02:06

at.


1 Answers

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.

like image 164
Avinash Raj Avatar answered Jun 30 '26 05:06

Avinash Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!