Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: matching for digits excluding some digits at a position

Tags:

regex

I have a string which has a pattern, say "xxx.xxx".

So first three are digits, then a . and then 3 more digits.

I want to check if first digit is always 3, and next 2 can be any digits except 30 and 40, rest can be anything.

My regex attempt is:

"3[^34][0-9]."

But it doesn't seem to work. Which part here is wrong?

like image 651
Mandroid Avatar asked Nov 28 '25 12:11

Mandroid


2 Answers

Try this: ^3(?!30|40)\d{2}\.\d{3}$

Test regex here: https://regex101.com/r/iCtKnB/1

^          matches the start of string
3          matches the number 3
(?!30|40)  checks if the next two numbers are not either 30 or 40
\d{2}      matches two digits if they are not 30 or 40
\.         matches period
\d{3}      matches the next three digits
$

Basically this will match any number of your pattern which begins with 3 not followed by 30 or 40 then a dot, followed by another three digits.

In your regex: "3[^34][0-9]."

  • 3 > This checks the number starts with 3
  • [^34] > then the Next digit is not 3 or 4
  • [0-9] > followed by one digits which can be 0 to 9
  • . > followed by any other char that is not white spaces

So your requirements were not being checked in this regex.

like image 116
anotherGatsby Avatar answered Dec 01 '25 15:12

anotherGatsby


In case lookaheads are not supported you can use:

^3(?:[0-25-9][0-9]|[34][1-9])\.[0-9]{3}$

RegEx Demo

like image 43
anubhava Avatar answered Dec 01 '25 17:12

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!