Reputation: 160
So I have a regex that identifies an invalid pattern for my input, I would like to be able to reverse it so that instead of matching invalid cases it matches with valid cases. Here is the invalid regex:
^(?=\d{6}$)(?:(\d)\1{5,}|012345|123456|234567|345678|456789|567890|098765|987654|876543|765432|654321|54321)$
Ideally to match positive cases it should ensure:
I have tried replacing the non capture group with a negative lookahead, however as I'm not familiar with the finer syntax for regex I'm not positive if this is simply an input mistake or if I need to change the regex somewhere else
EDITS While I know this could be handled by javascript I would like to handle it with regex to leverage the Foundations error handling
Upvotes: 1
Views: 267
Reputation: 10940
You can use this regex:
/(?=^(\d){6}$)(?!^\1{6})(?!^(?:012345|123456|234567|345678|456789|567890|098765|987654|876543|765432|654321|54321)$)^\d+$/
The regex uses look ahead
and starts by checking there's 6 digits
. It captures the last digit
which is used with a back reference to check, there's not 6 of the same digit
. It then use a negative look ahead
to compare with the list of invalid sequences.
Finally it matches the 6 digits
.
Upvotes: 2