Regex to match XML comments

I am looking for a Regex to match comments in XML documents:

<root>
<!-- match this
-->
<but>not this</but>
<!-- and also this
-->
</root>

I've tried <!--[^(-->)]*-->, which only matches single line comments, and <!--[\s\S\n]*--> which matches non-commented nodes as well.

1 Answer

The regex you're looking for would be:

<!--[\s\S\n]*?-->

Explanation:

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

If you have a comment inside a comment this will have issues though:

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

Highlighted in bold means a match

4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like