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

    match this 
<but>not this</but>
     and also this

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


The regex you're looking for would be:



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

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

  • This exact expression didn't work for me, but this did: <!--[\s\S\n]*?-->. Giving you the green check box for pointing out the "?" though, and the thorough explanation. – Dan Solovay Dec 5 '16 at 19:23
  • @DanSolovay I'll edit it to include your discovery of that Visual Studio quirk. – timotree Dec 5 '16 at 19:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.