【问题标题】:php regex to find nested multiline cfml commentsphp regex 查找嵌套的多行 cfml 注释
【发布时间】:2014-10-24 23:05:18
【问题描述】:

使用 php,我想要一个匹配 ColdFusion 支持的样式的嵌套和多行 cmets 的正则表达式:

1. <!--- this is a single comment line --->

2. <!---
multiline
comment
--->

3. <!---
multiline <!--- nested --->
comment <!--- comment --->
--->

所有这三种情况都是单一有效的 cfml cmets。我发现许多正则表达式适用于前两种情况,但不是第三种情况,这是真正的熊。任何帮助表示赞赏。

【问题讨论】:

    标签: php regex nested comments multiline


    【解决方案1】:

    你需要使用递归模式:

    <!---(?>[^<-]+|-(?!-->)|<(?!!---)|(?R))*--->
    

    详情:

    <!---
    (?>              # open an atomic group
        [^<-]+       #   all that is not a < or a -
      |              #  OR
        -(?!-->)     #   a - not followed by -->
      |              #  OR
        <(?!!---)    #   a < not followed by !---
      |              #  OR
        (?R)         #   recursion (repeat the whole pattern itself)
    )*               # close the atomic group, repeat zero or more times
    --->
    

    【讨论】:

      【解决方案2】:

      您可以使用带有 gs 选项的递归 PCRE 正则表达式:

      (?<comment><!---(?(?=<!---)\g<comment>|.)*?--->)
      

      DEMO

      故障(x 模式):

      (?<comment>         # define group "comment"
        <!---             # match a "<!---"
        (?(?=<!---)       # is the next sequence a "<!---"
          \g<comment>     #   yes: match a comment (recurse)
          |.              #   no: match a character
        )*?               # and repeat
        --->              # until a "--->"
      )                   # close "comment" definition
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-06
        • 2019-04-13
        • 2011-10-31
        • 1970-01-01
        • 2021-06-07
        • 2017-05-27
        • 1970-01-01
        • 2022-01-23
        相关资源
        最近更新 更多