Regex to Match HTML Comments
Match HTML comments including multi-line content with this regex pattern. Captures everything between <!-- and --> delimiters. Free regex tester.
Regular Expression
/<!--[\s\S]*?-->/g
Token Breakdown
| Token | Description |
|---|---|
| < | Matches the literal character '<' |
| ! | Matches the literal character '!' |
| - | Matches the literal character '-' |
| - | Matches the literal character '-' |
| [\s\S] | Character class — matches any one of: \s\S |
| *? | Matches the preceding element zero or more times (lazy/non-greedy) |
| - | Matches the literal character '-' |
| - | Matches the literal character '-' |
| > | Matches the literal character '>' |
Detailed Explanation
This regex matches HTML comments, including those spanning multiple lines. Here is the token-by-token breakdown:
— Matches the literal closing HTML comment delimiter. The two hyphens followed by a greater-than sign end the comment.The g flag enables global matching so all comments in the document are found, not just the first one. This pattern is useful for stripping comments from HTML before processing, extracting conditional comments for IE compatibility, or analyzing HTML source code. Note that nested comments are not valid in HTML, so this simple pattern handles the standard case well. For edge cases involving CDATA sections or server-side includes within comments, additional patterns may be needed.
Example Test Strings
| Input | Expected |
|---|---|
| <!-- simple comment --> | Match |
| <!-- multi line --> | Match |
| <div>not a comment</div> | No Match |
| <!- not a comment -> | No Match |
| <!-- nested <!-- --> --> | Match |
Try It — Interactive Tester
Match Highlighting(3 matches)
Matches & Capture Groups
15 charsFlags: gMatches: 3Ctrl+Shift+C to copy regex