【问题标题】:Capturing HTML comments using Regex but ignoring a certain comment使用正则表达式捕获 HTML 注释但忽略某个注释
【发布时间】:2019-04-04 04:17:05
【问题描述】:

我想捕获 html cmets,但特定注释除外,即

 <!-- end-readmore-item --> 

目前,我可以使用下面的正则表达式成功捕获所有 HTML cmets,

(?=<!--)([\s\S]*?)-->

为了忽略指定的注释,我尝试了前瞻和后瞻断言,但在正则表达式的高级级别上是新手,我可能错过了一些东西。

到目前为止,我已经能够使用环视设计以下正则表达式,

^((?!<!-- end-readmore-item -->).)*$

我希望它忽略 end-readmore-item 评论,只捕获其他 cmets,例如,

<!-- Testing-->

但是,它完成了这项工作,但也捕获了我也想被忽略的常规 HTML 标记。

我一直使用下面的html代码作为测试用例,

<div class="collapsible-item-body" data-defaulttext="Further text">Further 
text</div>
<!-- end-readmore-item --></div>
</div>
&nbsp;<!-- -->
it only should match with <!-- --> but it's selecting everything except <!-- 
end-readmore-item -->
the usage of this is gonna be to remove all the HTML comments except <!-- 
end-readmore-item -->

【问题讨论】:

    标签: regex regex-negation regex-lookarounds


    【解决方案1】:

    您可以使用以下模式:

    <!--(?!\s*?end-readmore-item\s*-->)[\s\S]*?-->
    

    Regex101 demo.

    细分:

    <!--                    # Matches `<!--` literally.
    (?!                     # Start of a negative Lookahead (not followed by).
        \s*                 # Matches zero or more whitespace characters.
        end-readmore-item   # Matches literal string.
        \s*                 # Matches zero or more whitespace characters.
        -->                 # Matches `-->` literally.
    )                       # End of the negative Lookahead.
    [\s\S]*?                # Matches any character zero or more time (lazy match), 
                            # including whitespace and non-whitespace characters.
    -->                     # Matches `-->` literally.
    

    这基本上意味着:

    匹配&lt;!-- not 后跟 [一个空格* + end-readmore-item + 另一个空格* + --&gt;]其中 后跟任意数量的字符,然后紧跟 --&gt;


    *一个可选空格重复零次或多次。

    【讨论】:

    • 这对我有用!能否请您也向我解释一下这个表达方式?
    【解决方案2】:

    您的否定前瞻断言非常接近,您只需将其修改如下:

    <!--((?!end-readmore-item).)*?-->
    

    *? 非贪婪匹配。

    这将匹配除注释正文中包含字符串 end-readmore-item 的所有 cmets。

    【讨论】:

    • 不错的一个!我唯一的批评是,这会检查评论的 每个字符 的 Lookahead,这是低效的,特别是如果您要检查长 cmets。
    猜你喜欢
    • 1970-01-01
    • 2014-09-02
    • 2013-07-05
    • 1970-01-01
    • 2020-10-26
    • 2018-03-28
    • 2010-11-08
    • 2014-07-26
    • 1970-01-01
    相关资源
    最近更新 更多