2

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?

Jeremy French
  • 11,707
  • 6
  • 46
  • 71
  • 1
    Yes, this is how you have to do it with regular expressions because at best they deal with numerals, not numbers. Add ^ and $ to the beginning and and to filter numbers outside your range. Is there a reason you need to check with a regular expression, an awkward tool in this context? – Greg Bacon Jun 23 '09 at 12:48
  • Thanks for the answers, and confirming what I thought I knew. – Jeremy French Jun 24 '09 at 10:42

3 Answers3

9

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.

Jeremy Smyth
  • 23,270
  • 2
  • 52
  • 65
4

The only other way I can think of would be to keep the regex simple (item[0-9]{3}) and do the rest of the checking in code. Regular expressions can't solve all problems :)

Jon Grant
  • 11,369
  • 2
  • 37
  • 58
1

What about matching the digits and then doing a numeric comparison?

vinko@mithril:~$ more val.php
<?php
function validateItem($item) {

    $matches = array();
    preg_match("/item(\d+)/",$item, $matches);
    if ($matches[1] < 355 || $matches[1] > 502) return false;
    return true;

}

var_dump(validateItem("item305"));
var_dump(validateItem("item355"));
var_dump(validateItem("item356"));
var_dump(validateItem("item5454"));
?>
vinko@mithril:~$ php val.php
bool(false)
bool(true)
bool(true)
bool(false)
Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373