Home > Software engineering >  I need a regex to invalidate all the same digits in a phone number
I need a regex to invalidate all the same digits in a phone number

Time:01-10

The regex should invalidate the phone number if all the digits are same. For eg - 0000000,1111111,2222222,etc. should be invalid. But on the other hand if I enter 11111112 then this should be valid as it contains another digit as well. The length of the regex should be between 7 to 15.

I tried with this (?!(\d)\1{6})([0-9]{7,15}) but the same is not working as expected. If there is any better way, please suggest me the same.

CodePudding user response:

You can use a positive lookahead pattern at the beginning to assert that there exists at least a digit whose following digit isn't the same:

^(?=.*(\d)(?=\d)(?!\1))\d{7,15}$

Demo: https://regex101.com/r/tn9kJd/1

CodePudding user response:

You could use a single negative lookahead to rule out the same digits 0-9 as in C# using \d could match more digits than only 0-9:

^(?!([0-9])\1 $)[0-9]{7,15}$

The pattern matches:

  • ^ Start of string
  • (?! Negative lookahead, assert that to the right is not
    • ([0-9])\1 $ Capture a digit 0-9 in group 1 and repeat that same digit using a backreference \1 one more times till the end of the string
  • ) Close the lookahead
  • [0-9]{7,15} Match 7-15 digits in the range 0-9
  • $ End of string

See a regex101 demo.

  • Related