I am trying a simple regex to match exactly 5 digits from a string. However, this pattern matches for 5 and more than 5.
preg_match_all('#[0-9]{5}+#', 'one two 412312 three (51212 four five)', $matches);
print_r($matches);
Result:
Array(
[0] => Array
(
[0] => 41231
[1] => 51215
)
)
I need it to match exactly 5 digits.
Thanks.
You can use word boundaries here and remove the +
quantifier after the range operator.
preg_match_all('~\b\d{5}\b~', $str, $matches);
As stated in the comments, if you need to match the five digits in a51212a
but not 412312
you can use a combination of lookaround assertions.
preg_match_all('~(?<!\d)\d{5}(?!\d)~', $str, $matches);
Try this:
preg_match_all('(\b\d{5}\b)', 'one two 412312 three (51212 four five)', $matches);
print_r($matches);
It matches every group of 5 digits.
您可以为此使用前行和-后: (?<!\\d)[0-9]{5}(?!\\d)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.