Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

php

pcre

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!

like image 790
Alfonso Khiew Avatar asked Mar 13 '23 07:03

Alfonso Khiew


1 Answers

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
like image 124
rock321987 Avatar answered Mar 15 '23 04:03

rock321987