gpt4 book ai didi

php - 字符串上的正则表达式否定回顾

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:44:41 24 4
gpt4 key购买 nike

如果一个字符串存在但不是立即在另一个字符串之前,我似乎无法找到一种不返回匹配项的方法。

如果一个字符串立即存在于另一个字符串之前,我可以不返回匹配项,如下所示。

$string = 'Stackoverflow hello world foobar test php';

$regex = "~(Stackoverflow).*?(?<!(test\s))(php)~i";

if(preg_match_all($regex,$string,$match))
print_r($match);

在这个例子中,如果我们有单词 Stackoverflowphp 但只有当单词 test(与空格字符)在单词 php 之前不存在。

这不会返回任何好的结果。

现在假设我想匹配 php 但前提是单词 foobar 不存在于 Stackoverflowphp 之间,我以为我可以做到以下几点。

$string = 'Stackoverflow hello world foobar test php';

$regex = "~(Stackoverflow).*?(?<!(foobar)).*?(php)~i";

if(preg_match_all($regex,$string,$match))
print_r($match);

(我已经将字符串背后的负面外观更改为(foobar),并在之后添加了.*?)

我还想说,我不能总是知道foobarphp 之间会存在哪些词,有时没有,有时有200 个,但我确实知道一些定位信息(在 Stackoverflow 之后和 php 之前)。

最佳答案

我会使用否定前瞻来确保字符串“foobar.*php”在“stackoverflow”之后不存在并且由于您想捕获 php,所以我将其放入捕获组中。像这样的东西:

Stackoverflow(?:(?!foobar.*php).)*(php)

请注意,这会导致在每个字符之后进行检查

关于php - 字符串上的正则表达式否定回顾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22393888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com