Spencer
Spencer

Reputation: 2245

Regex to match a phone number that is not composed of all the same number

I need a regex that will match phone numbers that are not all composed of the same number. I'm talking about a 10 digit phone number that looks like this (123)123-1234. I've seen patterns that will match phones that are all the same, but I'm trying to match the opposite.

I've come up with this which is oh so close, but not quite there.

^\((\d)(?!\1{2})\d{2}\)(?!\1{3})\d{3}-(?!\1{4})\d{4}$

The only place this fails is when the area code is all the same number, everything else seems to work great. So it will fail on something like this (888)123-1234, but will pass on (886)123-1234

How do I get it to accept that last hold out?

I've seen similar questions

how to Validate a Phone number so that it should not allow all same numerics like 99999999999 or 11111111111 in java

but this one doesn't account for the () and -, also it's matching the opposite of what I want.

and

Regex to block a phone number that contains same digit more than 4 times successively?

this kind of looks promising, but it doesn't account for the () and -.

Upvotes: 2

Views: 802

Answers (1)

anubhava
anubhava

Reputation: 785296

You can use this negative lookahead regex:

^\((\d)(?!\1{2}\)\1{3}-\1{4}$)\d{2}\)\d{3}-\d{4}$

RegEx Demo

Negative lookahead (?!\1{2}\)\1{3}-\1{4}$) will only fail the match if same digit is repeated all over from start to end.

Upvotes: 1

Related Questions