Reputation: 12157
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?
Upvotes: 2
Views: 7926
Reputation: 23493
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.
Upvotes: 9
Reputation: 340191
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)
Upvotes: 1
Reputation: 11530
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 :)
Upvotes: 4