“*”和“?”之间有什么区别?在php preg匹配?

时间:2012-01-27 21:40:19

标签: php regex

使用“*”或“?”之间有区别吗?在php preg_match?还是有例子吗?

<?php

// the string to match against
$string = 'The cat sat on the matthew';

// matches the letter "a" followed by zero or more "t" characters
echo preg_match("/at*/", $string);

// matches the letter "a" followed by a "t" character that may or may not be present
echo preg_match("/at?/", $string);

2 个答案:

答案 0 :(得分:6)

*匹配0或更多

?匹配0或1

在您的特定测试的上下文中,您无法区分,因为*?匹配未锚定或没有任何跟随它们 - 它们都匹配任何包含a的字符串,后跟是否t

如果您在匹配字符后面有,则差异很重要,例如:

echo preg_match("/at*z/", "attz"); // true
echo preg_match("/at?z/", "attz"); // false - too many "t"s

与你同在:

echo preg_match("/at*/", "attz"); // true - 0 or more
echo preg_match("/at?/", "attz"); // true - but it stopped after the
                                  // first "t" and ignored the second

答案 1 :(得分:3)

// matches the letter "a" followed by zero or more "t" characters

// matches the letter "a" followed by a "t" character that may or may not be present

来源:You