我有这样的正则表达式:RegEx验证4位和5位数字?
if(preg_match("@^\d{4}[email protected]", basename($entry, ".php"))) {
--do something here--
}
该条件仅适用于4个位数。但我需要验证4位数字和5位数字。如何使它工作来验证5位数字呢?谢谢!
我有这样的正则表达式:RegEx验证4位和5位数字?
if(preg_match("@^\d{4}[email protected]", basename($entry, ".php"))) {
--do something here--
}
该条件仅适用于4个位数。但我需要验证4位数字和5位数字。如何使它工作来验证5位数字呢?谢谢!
大括号可以采取一个范围的低端和高端,所以{4,5}
应该工作。
+1为正则表达式解释。我鼓励你也提供一个代码示例。 –
下面是你可以在命令行上运行的东西:'php -r'$ pattern =“/^\ d {4,5} /”; preg_match($ pattern,“12345678”,$ a);的print_r($ A);'' – LazyMonkey
if(preg_match("@^\d{4,5}[email protected]", basename($entry, ".php"))) {
--do something here--
}
代替
if(preg_match("@^\d{4}[email protected]", basename($entry, ".php"))) {
使用
if(preg_match("@^\d{4,5}[email protected]", basename($entry, ".php"))) {
作为替代正则表达式,可以考虑像ctype_digit()
和strlen()
简单的功能。
$filename = basename($entry, ".php");
$length = strlen($filename);
if (($length >= 4 && $length <= 5) && ctype_digit($filename)) {
// your code
}
*另见[打开源使用RegexBuddy替代(http://stackoverflow.com/questions/89718/is-there)和[在线的正则表达式的测试](http://stackoverflow.com/questions/32282/regex-testing),或者[RegExp.info](http://regular-expressions.info/)。 – mario