duanniesui6391 2018-03-20 20:24
浏览 116
已采纳

RegEx:在分隔符之前或之后

Consider the following

use namespace;

class name impl... {

    use Trait;
}

How would I go about it, if I would like to extract either the use from before the class definition or the one after? Well in the above example it would be simple enough, but if it should also work on an actual code file with multiple use in both places and maybe not even grouped together, but with other things in between and also with all line chars removed?

It's easy enough to get them all, but I want it to either stop when it reaches the class or begin from the class. Just can't seam to get anything to work correctly.

Lines, comments and literals is stripped, so these should not be taken into consideration.

  • 写回答

2条回答 默认 最新

  • dongqian6234 2018-03-21 02:19
    关注

    Removing blocks is not bad, but I need to get them all, incl the ones in the inner scope, I just need to know which is which.

    This is apparently to much for a single RegExp to handle, so this is what I did. Just in case others reading this is looking for an answer.

    Use something to locate the offset starting position of the class declaration.

    /\b(class|interface|trait)\s+[\w]+.*{/s
    

    This combined with preg_match and it's PREG_OFFSET_CAPTURE flag will provide you with the offset.

    Then extract all of the use clauses, inner and outer scope.

    /\buse\s+(?<full>([\w\\\]+(?:\s+as\s+[\w]+)?(?:\s*[,]\s*)?)+)(?:(?<=[\\\]){(?<inline>.*)})?\s*[;{]/
    

    Use this with preg_match_all, using PREG_SET_ORDER|PREG_OFFSET_CAPTURE, which will include the offset of each match.

    Now simply compare each offset with the one extracted in the beginning. If it's lower, it's a reference clause. If it's higher, it's a trait clause.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dsf4354353452 2018-03-21 01:13
    关注

    In order to detect use clauses occuring in the outermost scope, you need to remove all (nested) blocks of {...}. You cannot do it in a single expression (due to unlimited depth) but if you want you may apply block removal in a loop:

    $s = <your code>;
    $prev_s = "";
    while ($s != $prev_s) {
        $prev_s = $s;
        $s = preg_replace('\{[^}]*\}','',$s);
    }
    

    Now you may collect the outer use clauses

    $outer_uses = preg_match_all('\buse\s+(\w+)', $s);
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Google Chrome 所有页面崩溃,三种解决方案都没有解决,我崩溃了
  • ¥20 使用uni-app发起网络请求,获取重定向302返回的cookie
  • ¥20 手机外部浏览器拉起微信小程序支付 (相关搜索:微信小程序)
  • ¥20 怎样通过一个网址找到其他同样模版的网址
  • ¥30 XIAO esp32c3 读取FDC2214的数据
  • ¥15 在工控机(Ubuntu系统)上外接USB蓝牙硬件进行蓝牙通信
  • ¥15 关于PROCEDURE和FUNCTION的问题
  • ¥100 webapi的部署(标签-服务器)
  • ¥20 怎么加快手机软件内部计时的时间(关键词-日期时间)
  • ¥15 C语言除0问题的检测方法