Regex, preg_match返回太多结果


Regex, preg_match, returns too many results?

我的代码工作得很好,但我不明白结果。我的目标是确保传入的值是以下格式之一:

    00000 - 0000
  • 000000000
  • 00000
PHP:

$str = '12345-6789';
preg_match('/^[0-9]{5}(-?[0-9]{4})?$/', $str, $found);
print_r($found);

返回:

Array
(
    [0] => 12345-6789
    [1] => -6789
)

为什么我得到第二个结果[1] => -6789 ?

谢谢!

这是因为您使用()时有一个捕获组:

$str = '12345-6789';
preg_match('/^[0-9]{5}(-?[0-9]{4})?$/', $str, $found);
//                    ^          ^
print_r($found);

您可以使用?:来确保它不被捕获:

$str = '12345-6789';
preg_match('/^[0-9]{5}(?:-?[0-9]{4})?$/', $str, $found);
//                     ^^
print_r($found);

(-?...周围的括号导致它被捕获。$found的第0个条目包含整个匹配,随后的每个条目包含每个捕获的组。这可能没问题,但如果您绝对不想捕获,则可以使用非捕获组:

(?:-?[0-9]{4})?

-()也就是capture block里面,这些块是PHP会返回的匹配。

$str = '12345-6789';
preg_match('/^[0-9]{5}-?([0-9]{4})?$/', $str, $found);
print_r($found);