正则表达式匹配 XML 注释

Dan*_*vay 7 regex

我正在寻找一个正则表达式来匹配 XML 文档中的注释:

<root>
<!-- 
    match this 
-->
<but>not this</but>
<!--
     and also this
-->
</root>
Run Code Online (Sandbox Code Playgroud)

我试过<!--[^(-->)]*-->,它只匹配单行注释,<!--[\s\S\n]*-->也匹配非注释节点。

tim*_*ree 8

您正在寻找的正则表达式是:

<!--[\s\S\n]*?-->
Run Code Online (Sandbox Code Playgroud)

解释:

 <!--               All comments must begin with this
     [\s\S\n]       Any character (. doesn't allow newlines)
             *      0 or more of the previous thing ([\s\S\n])
              ?     As few of the previous thing as possible while still matching
               -->  All comments must end with this
Run Code Online (Sandbox Code Playgroud)

如果您在评论中有评论,这将有问题:

<!-- Documentation
This program documents itself using comments of the type <!-- -->
-->

以粗体突出显示表示匹配