正则表达式匹配返回意外结果
Regex match returning unexpected results
我正在尝试正则表达式匹配,但得到了意想不到的结果。我做错了什么?
$text = "one two three?four five six?";
preg_match("~(.+?)(?:\?)?~", $text, $match);
print_r($match);
结果:
Array ( [0] => o [1] => o )
预期结果:
Array ( [0] => one two three? [1] => one two three )
您需要删除非捕获组旁边的 ?
,这使得该非捕获组成为可选的。由于 ?
是可选的,因此 (.+?)
非贪婪模式应该只匹配和捕获第一个字符。
preg_match("~(.+?)\?~", $text, $match);
我正在尝试正则表达式匹配,但得到了意想不到的结果。我做错了什么?
$text = "one two three?four five six?";
preg_match("~(.+?)(?:\?)?~", $text, $match);
print_r($match);
结果:
Array ( [0] => o [1] => o )
预期结果:
Array ( [0] => one two three? [1] => one two three )
您需要删除非捕获组旁边的 ?
,这使得该非捕获组成为可选的。由于 ?
是可选的,因此 (.+?)
非贪婪模式应该只匹配和捕获第一个字符。
preg_match("~(.+?)\?~", $text, $match);