简体   繁体   English

是否可以在正则表达式中将两个单独的环视/零宽度断言(即,lookbehind / look-behind)相加?

[英]Is it possible to AND two separate lookaround/zero-width assertions (i.e. lookbehind/look-behind) in a regular expression?

I'm using Perl for this regular expression question, but it would be good to know if it applies to PHP, as well. 我正在使用Perl来解决这个正则表达式问题,但是最好知道它是否也适用于PHP。

I need to comment out all print statements or all things that start with print in a PHP file. 我需要注释掉所有打印语句或PHP文件中所有以print开头的内容。 It looks something like this: 看起来像这样:

<?php
    // Description of file
    ...
    print("Foobar");
    // print("Foo");
    //print("bar");
    // Open and print file
    function printtemplate($file) {
    ...
    }
    ...
    printtemplate($file);
    ...  
?>

To start with, I formulated a regular expression like this: 首先,我制定了如下正则表达式:

((?<!function )|(?<!//))print

It obviously does not work because the | 它显然不起作用,因为| is an OR. 是一个OR。 I'm looking for an AND so that both negative look-behind assertions need to be true. 我正在寻找AND,因此两个否定的后向断言都必须为真。 Does the AND construct exist in some form in regular expressions or is there a way to simulate one? AND构造是否以某种形式存在于正则表达式中,或者有一种方法可以模拟它?

Ultimately, I want the php file to look like the following, after the regular expression is applied: 最终,在应用正则表达式之后,我希望php文件如下所示:

<?php
    // Description of file
    ...
    //print("Foobar");
    // print("Foo");
    //print("bar");
    // Open and print file
    function printtemplate($file) {
    ...
    }
    ...
    //printtemplate($file);
    ...  
?>

Any help would be appreciated. 任何帮助,将不胜感激。 Thank you. 谢谢。

Just put them next to each other. 只是将它们彼此相邻。 That's it. 而已。 It will create AND effect, since you need to pass both look-around before being able to match anything that comes after them. 它将创建AND效果,因为您需要先传递两个环顾四周,然后才能匹配它们之后的所有内容。

In your case, it would be: 在您的情况下,它将是:

(?<!function )(?<!//)print

However, note that the regex above will return false positive, which causes more comments to be added than necessary. 但是,请注意,上面的正则表达式将返回假肯定,这将导致添加不必要的注释。 Demo . 演示

For PCRE (used in PHP), look-behind assertion requires the pattern to be strictly fixed-length, so it is not possible to use look-behind assertion to check in all cases whether print is being commented out or not to exclude it. 对于PCRE(在PHP中使用),后置断言要求模式严格地固定长度,因此不可能在所有情况下都使用后置断言检查print是否被注释掉或不将其排除。 @mpapec's answer gives one solution that is applicable for well-written code, and has better coverage than your regex with look-behind. @mpapec的答案提供了一种适用于编写良好代码的解决方案,并且比带有正则表达式的正则表达式具有更好的覆盖范围。

这是适用于给定示例的简单方法,

s|^ (\s*) (print) |$1//$2|xmg;

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

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