2

I'm using Perl for this regular expression question, but it would be good to know if it applies to PHP, as well.

I need to comment out all print statements or all things that start with print in a PHP file. 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. I'm looking for an AND so that both negative look-behind assertions need to be true. Does the AND construct exist in some form in regular expressions or is there a way to simulate one?

Ultimately, I want the php file to look like the following, after the regular expression is applied:

<?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.

4

2 回答 2

3

只需将它们放在一起即可。而已。它将创建AND效果,因为您需要通过两个环视才能匹配它们之后的任何内容。

在您的情况下,它将是:

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

但是,请注意,上面的正则表达式将返回误报,这会导致添加不必要的评论。演示

对于 PCRE(在 PHP 中使用),look-behind 断言要求模式是严格固定长度的,因此不可能使用look-behind 断言在所有情况下检查是否print被注释掉或不排除它。@mpapec 的答案提供了一种适用于编写良好的代码的解决方案,并且比您的正则表达式具有更好的覆盖率。

于 2013-05-11T17:29:37.603 回答
2

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

s|^ (\s*) (print) |$1//$2|xmg;
于 2013-05-11T17:39:27.443 回答