regexhelper
Test a pattern. Copy a ready-made one. No signup.

Regex to Match an HTML Comment

Copy the pattern, paste your markup, and watch each comment light up. Below: why the lazy quantifier matters.

/ /

What this pattern matches

It matches an HTML comment from <!-- to the next -->, including comments that span several lines.

Part by part

<!-- — the literal comment opener.

[\s\S]*? — any character, including newlines, matched lazily so it stops at the first closer.

--> — the literal comment closer.

Why lazy?

A greedy .* would swallow everything up to the last --> on the page, merging separate comments. The lazy *? stops at the first one. [\s\S] is used instead of . so it works without the dotall flag.

Use it in your code

Python
import re
text = "<div><!-- header --><p>Hi</p><!-- multi\nline\ncomment --></div>"
pattern = r'''<!--[\s\S]*?-->'''
for m in re.finditer(pattern, text):
    print(m.group())
JavaScript
const text = "<div><!-- header --><p>Hi</p><!-- multi\nline\ncomment --></div>";
const re = new RegExp(String.raw`<!--[\s\S]*?-->`, "g");
console.log(text.match(re));

FAQ

Why [\s\S] instead of a dot?

In most flavours . does not match newlines by default. [\s\S] matches any character including line breaks, so multi-line comments work everywhere.

Can I use this to strip comments?

Yes — replace matches with an empty string. But for robust HTML processing a parser is safer than regex.

Does it handle conditional comments?

Yes, they are still <!-- ... --> comments, so they match; the inner content is captured like any other.