我使用Perl来解决这个正则表达式问题,但是最好知道它是否也适用于PHP。
我需要在PHP文件中注释掉所有print语句或所有以print开头的内容。它看起来像这样:
<?php
// Description of file
...
print("Foobar");
// print("Foo");
//print("bar");
// Open and print file
function printtemplate($file) {
...
}
...
printtemplate($file);
...
?>首先,我制定了一个正则表达式,如下所示:
((?<!function )|(?<!//))print它显然不起作用,因为|是OR。我正在寻找一个AND,这样两个负面的回溯断言都需要为真。AND结构在正则表达式中是否以某种形式存在,或者有没有方法来模拟?
最终,在应用正则表达式之后,我希望php文件看起来像下面这样:
<?php
// Description of file
...
//print("Foobar");
// print("Foo");
//print("bar");
// Open and print file
function printtemplate($file) {
...
}
...
//printtemplate($file);
...
?>任何帮助都将不胜感激。谢谢。
发布于 2013-05-12 01:29:38
把它们放在一起就行了。就这样。它将创建并生效,因为您需要通过这两个环视,然后才能匹配它们后面的任何内容。
在您的情况下,它将是:
(?<!function )(?<!//)print但是,请注意,上面的正则表达式将返回假阳性,这会导致添加更多的注释。。
对于PCRE (在PHP中使用),回溯断言要求模式必须是严格固定长度的,因此不可能在所有情况下都使用回溯断言来检查print是否被注释掉或未将其排除。@mpapec的回答给出了一种适用于编写良好的代码的解决方案,并且比您的regex和look-look具有更好的覆盖率。
发布于 2013-05-12 01:39:27
这是一种简单的方法,它适用于给定的示例,
s|^ (\s*) (print) |$1//$2|xmg;https://stackoverflow.com/questions/16499782
复制相似问题