正则表达式为2个字母,后跟4位数字 [英] Regex for 2 letters followed by 4 digits
问题描述
字符串应以"S2"开头,后跟任意4位数字.
The string should begin with "S2" followed by any 4 digits.
匹配的字符串是"S20165".
A matching string is "S20165".
我正在尝试以下代码,但是即使有5或6位数字,它也始终会回显OK.
I'm trying with the following code, but it always echos OK even when there are 5 or 6 digits.
$string='S20104';
if(preg_match('/S2[0-9]{4}/', $string)){
echo 'OK';
}
else{
echo 'NOT OK';
}
推荐答案
您必须使用锚点:
/^S2[0-9]{4}$/
^
匹配字符串的开头,而$
匹配字符串的结尾,因此这将确保您检查完整的字符串,而不仅仅是子字符串.
^
matches the start of the string and $
matches the end of the string, so this will make sure that you check the complete string and not just a substring.
您也可以使用\d
代替[0-9]
.在PHP中,只要您不使用'u'模式修饰符,preg *函数不支持Unicode,因此两者是等效的.
You can also use \d
instead of [0-9]
. In PHP, as long as you do not use the 'u' pattern modifier, preg* functions are not Unicode aware, so the two are equivalent.
这篇关于正则表达式为2个字母,后跟4位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!