Reputation: 267317
I need to check if a string is in the format: xxx[y-z]
Where y and z are two numbers. E.g y can be 1000 and z can be 2000, in which case these will be valid:
xxx1000 xxx1500 xxx1900 xxx2000
Is there a way to accomplish this in regex?
Upvotes: 1
Views: 1780
Reputation: 116538
I don't see the point in using a regex here, especially if y
and z
are variables. Use the regex to test the format, but then take the right-most n characters (capturing it in a group is the easiest), try to parse it into an integer and test if it's in the range.
If y
and z
are constant though, sure go ahead:
xxx(2000|1[0-9]{3})$
Upvotes: 3
Reputation: 324840
This kind of evalution should not really be in a regex if you can help it. You can use a regex to run a test on the format, but use other functions to test the content:
$in = "xxx1234";
if( preg_match("/^xxx(\d{4})$/",$in,$m) && $m[1] >= 1000 && $m[1] <= 2000) {
// ok!
}
Upvotes: 2