简体   繁体   中英

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 -.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM