I want regex such that it accept any 9 digit number except 123456789 and 987654321

I want regex such that it accept any 9 digit number except 123456789 and 987654321

Problem Description:

Acceptable input : any 9 digit number

Not acceptable : 123456789 and 987654321

I am using [0-9]{9} but I want extra condition as well

Solution – 1

I would suggest that, as you only have two exceptions, you write the regex to confirm it’s a 9-digit numeric number, and then special case the two edge cases you mention. Not as technically challenging, but much easier to read the code.

Solution – 2

Try:

^(?!123456789|987654321)d{9}$

Regex demo.


^ – beginning of string

(?!123456789|987654321) – don’t continue matching if 123456789 or 987654321 is found

d{9} – match 9 digits

$ – end of string

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject