我正在尝试一个简单的正则表达式来匹配字符串中的5位数字。然而,这种模式与5和5以上匹配。
preg_match_all('#[0-9]{5}+#', 'one two 412312 three (51212 four five)', $matches);
print_r($matches);
结果:
Array(
[0] => Array
(
[0] => 41231
[1] => 51215
)
)
我需要它正好匹配5位数字。
谢谢。
您可以在此处使用单词边界,并删除范围运算符后的+
量词。
preg_match_all('~'b'd{5}'b~', $str, $matches);
如注释中所述,如果您需要匹配a51212a
中的五位数字,而不是412312
,则可以使用环视断言的组合。
preg_match_all('~(?<!'d)'d{5}(?!'d)~', $str, $matches);
试试这个:
preg_match_all('('b'd{5}'b)', 'one two 412312 three (51212 four five)', $matches);
print_r($matches);
它匹配每组5位数字。
您可以使用lookahead和-behinds:(?<!'d)[0-9]{5}(?!'d)