使用 Regex 捕获 HTML 评论但忽略特定评论

Capturing HTML comments using Regex but ignoring a certain comment

我想捕获 html 条评论,但特定评论除外,即

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

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

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

为了忽略指定的注释,我尝试了前瞻和后视断言,但作为 Regex 高级级别的新手,我可能遗漏了一些东西。

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

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

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

<!-- 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 -->

您可以使用以下模式:

<!--(?!\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.

这基本上意味着:

Match <!-- that is not followed by [a whitespace* + end-readmore-item + another whitespace* + -->] and which is followed by any amount of characters then immediately followed by -->.


* 可选 空白重复零次或多次。

你的否定前瞻断言非常接近,你只需要修改如下:

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

其中 *? 非贪婪匹配。

这将匹配除评论正文中包含字符串 end-readmore-item 之外的所有评论。