I want to match strings that do not contain more than 3 of the same character repeated in a row. So:
- abaaaa [no match]
- abawdasd [match]
- abbbbasda [no match]
- bbabbabba [match]
Yes, it would be much easier and neater to do a regex match for containing the consecutive characters, and then negate that in the code afterwards. However, in this case that is not possible.
I would like to open out the question to x consecutive characters so that it can be extended to the general case to make the question and answer more useful.
Negative lookahead is supported in this case.
I'm answering this question :
Is there a regular expression for matching a string that has no more than 2 repeating characters?
which was marked as an exact duplicate of this question.
Its much quicker to negate the match instead
Use a negative lookahead with back references:
See live demo using your examples.
(.)
captures each character in group 1 and the negative look ahead asserts that the next 2 chars are not repeats of the captured character.To match strings not containing a character repeated more than 3 times consecutively:
^((.)\2?(?!\2\2))+$
How it works:
So, the number of
/2
in your whole expression will be the number of times you allow a character to be repeated consecutively, any more and you won't get a match.E.g.
^((.)\2?(?!\2\2\2))+$
will match all strings that don't repeat a character more than 4 times in a row.^((.)\2?(?!\2\2\2\2))+$
will match all strings that don't repeat a character more than 5 times in a row.Please be aware this solution uses negative lookahead, but not all not all regex flavors support it.