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.

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

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?