php - php preg匹配中的 "*"和 "?"有什么区别?

使用“*”或“?”有区别吗?在 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);

最佳答案

* 匹配 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

https://stackoverflow.com/questions/9040435/

相关文章:

visual-c++ - 为什么没有定义 PCTSTR 但定义了 LPCTSTR?

asp.net - Web API 可以将XML 转换成Json 吗?

logging - 如何在 Glassfish 中设置日志记录级别?

jquery - 如何使用 jQuery 取消按钮的提交

bash - 在 bash 中,如何在键入命令行时扩展 !$?

c# - 如何判断对象初始化程序何时完成

matlab - 将向量转置到三维

erlang - 在没有列表到字符串翻译的情况下格式化 Erlang 术语

sql - 如何从 SQL Server 获取数据库列表?

ruby-on-rails - Errno::ETIMEDOUT:连接超时 - connect(2)