php preg match中“*”和“?”之间有什么区别?

php preg match中“*”和“?”之间有什么区别?,php,regex,Php,Regex,使用*或*有区别吗?在php preg_比赛中?还是有一个例子 <?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

使用*或*有区别吗?在php preg_比赛中?还是有一个例子

<?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);
*匹配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
*匹配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
资料来源:


源代码:

代码中的注释已经描述了差异。@GregHewgill与preg_match,函数将在第一次匹配后停止,那么两者都是吗?和*将在完全相同的点的第一次匹配后停止,并返回1。区别是什么?@GregHewgill有点像,只是它们没有解释为什么在这种情况下这两个函数的行为相同。代码中的注释已经描述了区别。@GregHewgill与preg_match的函数将在第一次匹配后停止,所以两者都是?和*将在完全相同的点的第一次匹配后停止,并返回1。有什么区别吗?@GregHewgill有点像,只是他们没有解释为什么在这种情况下这两个人的行为是一样的。我不得不用拇指来猜你的答案…:我不得不用拇指猜出你的答案…:虽然问题中没有明确说明,但购买可能会导致一些混乱,不要忘记?作为一个像。*?@JonathanKuhn这样的非贪婪操作符,当然可以,但在这种情况下,它是一个修饰符,而不是一个匹配操作符。我知道,只是表明?有不止一个用途?。如果后来有人看到了?他们可能会感到困惑,认为这意味着任何一个字符,0或更多,0或1。虽然问题中没有明确说明,但购买可能会导致一些困惑,不要忘记?作为一个像。*?@JonathanKuhn这样的非贪婪操作符,当然可以,但在这种情况下,它是一个修饰符,而不是一个匹配操作符。我知道,只是表明?有不止一个用途?。如果后来有人看到了?他们可能会感到困惑,认为它意味着任何一个字符,0或更多,0或1。