简体   繁体   English

使用前瞻性否定断言的正则表达式

[英]regular expression using lookahead negative assertion

Using php I would like to detect something in a string depending on whether the part immediately after the matched part does not contain certain characters. 使用php我想根据匹配部分之后的部分是否不包含某些字符来检测字符串中的某些内容。 I think I may need to use a lookahead negative assertion but it is not working as I would expect so not sure. 我认为我可能需要使用前瞻性否定断言,但它不起作用,正如我期望的那样,因此不确定。 So for example: 因此,例如:

$string = 'test somerandomURL><b>apple</b> peach orange';

I want an expression that will detect everything up to the first > so long as <b>apple</b> does not immediately follow the first > 我想要一个表达式,它可以检测到第一个>之前的所有内容,只要<b>apple</b>不立即跟随第一个>

I tried 我试过了

if(preg_match("/test(.*)>(?!<b>apple<\/b>)(.*)/i",$string)){
echo 'true since <b>apple</b> does not follow > in string';
}else{
echo 'false since <b>apple</b> follows > in string';
}

When the string contains <b>apple</b> after the > it returns false as I expect and need but when I change the string to have <b>peach</b> after the > instead of <b>apple</b> it still returns false and I need it to return true. 当字符串<b>apple</b>后面包含<b>apple</b> ,它按我的期望和需要返回false,但是当我将字符串更改为在<b>peach</b>之后而不是<b>apple</b>它仍然返回false,我需要它返回true。 Without the bold tags it seems to work as I would expect. 没有粗体标签,它似乎可以正常工作。 Any ideas what I am doing wrong? 有什么想法我做错了吗?

You're doing a few things wrong, including not turning on error reporting because you have mismatched () 's and an / that needs escaping. 您在做一些错误的事情,包括由于您不匹配()和需要转义的/而没有打开错误报告。

The first problem is that .* is greedy. 第一个问题是。*是贪婪的。 So in your string it will match: test somerandomURL><b>apple</b> 因此,在您的字符串中它将匹配: test somerandomURL><b>apple</b>

Usually the solution to that is to make it lazy with .*? 通常,解决方案是使.*?变得懒惰.*? but because of the negative lookahead, laziness will still make it match up to a further > when apple is found. 但由于负先行的,懒惰仍然会让它匹配,以进一步>当发现苹果。

The solution is a negated character class. 解决方案是否定字符类。 [^>]* will match any char except > [^>]*将匹配任何字符,除了>

/test([^>]*)>(?!<b>apple<\/b>)(.*)/i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM