Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

number range in a regex

Tags:

regex

php

I may have a hole in my regex knowlege.

If I am trying to look for items in a string which may be in the numeric range "item[355-502]" is there an easy way to do this. as far as I can tell I would have to do something like

 (35[5-9]|3[6-9][0-9]|4[0-9][0-9]|50[0-2])

I know this also matches for 3550-5020 etc, that should be fine

This, indicates that this can't be done any other way, is this right. i'm in PHP is there a neater way to do this?

like image 388
Jeremy French Avatar asked Feb 27 '26 19:02

Jeremy French


1 Answers

This is a numeric problem rather than a string problem, so I fear your solution does not lie completely in a regex!

You will need to parse the digits and then perform numeric comparison, e.g.:

$input = whatever(); # gets something like "item[456]"

...then match with the following pattern:

preg_match("/item\[(\d+)\]/", $input, $match);

...to store the digits in memory, and then:

if($match[1] >= 355 and $match[1] <= 502){...

to check to see if the number is in range.

like image 189
Jeremy Smyth Avatar answered Mar 01 '26 09:03

Jeremy Smyth



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!