正则表达式数值范围,例如1000 - 2000?

正则表达式数值范围,例如1000  -  2000?

问题描述:

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?

我需要检查字符串的格式是否为:xxx [yz] p>

其中y和z是两个数字。 例如,y可以是1000,z可以是2000,在这种情况下,这些将是有效的: p>

xxx1000 xxx1500 xxx1900 xxx2000 p>

是否有 在正则表达式中实现此目的的方法吗? p> div>

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!
}

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})$