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条)

报告相同问题?

悬赏问题

  • ¥15 vhdl+MODELSIM
  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题