Alfonso Khiew Alfonso Khiew - 6 months ago 16
PHP Question

Regex where a number can start with 9 but not 999 consecutively

I'm trying to make a regex where:


  1. a number can start from 3,5,6 or 9

  2. the number cannot be starting with 999.



Thus for example,
93214211
is matched, but
99912345
should not be matched.

This is what I have for now which satisfies the first requirement:

^3|^5|^6|^9|[^...]}


I'm stuck at the 2nd requirement for a while now.
Thanks!

Answer

You can use negative lookahead like

^(?!999)[3569]\d{7}$ <-- assuming the number to be of 8 digits

Regex Demo

Regex Breakdown

^ #Start of string
  (?!999) #Negative lookahead. Asserts that its impossible to match 999 in beginning
  [3569] #Match any of 3, 5, 6 or 9
  \d{7} #Match 7 digits
$ #End of string