duandeng7132 2013-05-11 17:19
浏览 57
已采纳

是否有可能在正则表达式中AND两个单独的环视/零宽度断言(即lookbehind / look-behind)?

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.

  • 写回答

2条回答 默认 最新

  • dtdsbakn210537 2013-05-11 17:29
    关注

    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.

    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. @mpapec's answer gives one solution that is applicable for well-written code, and has better coverage than your regex with look-behind.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码