PHP Regex Negative Assertions 解释
PHP Regex Negative Assertions explanation
我试图理解 php 手册
PCRE regex syntax->Assertions
其中一项描述如下:
foo(?!bar) matches any occurrence of "foo" that is NOT followed by "bar".
虽然我尝试了以下结果的样本:
$text = "foobar foobar foobar fooabar";
$rules = "/foo(!?bar)/is";
preg_match_all($rules, $text, $matches);
$newLine = preg_replace($rules, "\thahaha", $text);
print_r( $matches );
echo "<br/>";
echo $rules. ":" .$newLine;
// result
Array ( [0] => Array ( [0] => foobar [1] => foobar [2] => foobar ) [1] => Array ( [0] => bar [1] => bar [2] => bar ) )
/foo(!?bar)/is: hahaha hahaha hahaha fooabar
所有 "foo" 替换为 "bar"。
那么,它实际上是相反的意思吗?还是我在其他地方遗漏了什么?
foo(?!bar) matches any occurrence of "foo" that is followed by "bar"???
提前致谢。
您的正则表达式是 foo(!?bar)
,它将检查 foo
然后 可选 !
然后 bar
,找到在前三个字符串中。 foobar foobar foobar
您放错了 !
和 ?
。
正确的正则表达式应该是 foo(?!bar)
,它将匹配最后一个字符串 fooabar
?表示可选表达式。在您的示例中,这意味着!可以存在或不存在。这意味着您正在匹配 bar
或 !bar
.
负面的前瞻是相反的。 (?!bar)
请记住,问号总是在括号开头之后
我试图理解 php 手册 PCRE regex syntax->Assertions
其中一项描述如下:
foo(?!bar) matches any occurrence of "foo" that is NOT followed by "bar".
虽然我尝试了以下结果的样本:
$text = "foobar foobar foobar fooabar";
$rules = "/foo(!?bar)/is";
preg_match_all($rules, $text, $matches);
$newLine = preg_replace($rules, "\thahaha", $text);
print_r( $matches );
echo "<br/>";
echo $rules. ":" .$newLine;
// result
Array ( [0] => Array ( [0] => foobar [1] => foobar [2] => foobar ) [1] => Array ( [0] => bar [1] => bar [2] => bar ) )
/foo(!?bar)/is: hahaha hahaha hahaha fooabar
所有 "foo" 替换为 "bar"。
那么,它实际上是相反的意思吗?还是我在其他地方遗漏了什么?
foo(?!bar) matches any occurrence of "foo" that is followed by "bar"???
提前致谢。
您的正则表达式是 foo(!?bar)
,它将检查 foo
然后 可选 !
然后 bar
,找到在前三个字符串中。 foobar foobar foobar
您放错了 !
和 ?
。
正确的正则表达式应该是 foo(?!bar)
,它将匹配最后一个字符串 fooabar
?表示可选表达式。在您的示例中,这意味着!可以存在或不存在。这意味着您正在匹配 bar
或 !bar
.
负面的前瞻是相反的。 (?!bar)
请记住,问号总是在括号开头之后