Skip to content

Regex for Html Comment — Pattern, Examples & Caveats

Pattern flags: g
<!--[\s\S]*?-->

This pattern matches HTML comments from <!-- to the nearest -->, using a lazy quantifier and [\s\S] to span newlines. It is used to strip or extract comments from HTML source. Web patterns deal with markup, styling and web identifiers: HTML tags and comments, CSS colors, Markdown links, slugs and source-code comments. They are handy for quick scanning and lightweight transforms, but markup is not a regular language, so anything structural or security-sensitive should use a real parser (DOM, CSS or Markdown) rather than regex alone. It uses the g flag(s). Apply it across text to collect every occurrence. The lazy *? stops at the first -->, which is correct for well-formed comments but can mis-handle nested or malformed comment syntax. [\s\S] is used instead of . because . does not match newlines without the s (dotAll) flag. HTML comments cannot legally contain -- inside; real parsers enforce this, but the regex is permissive. As with any regular expression, confirm its behavior in your target engine, test boundary and adversarial inputs, and watch for catastrophic backtracking before relying on it in production.

Advertisement
Ad slot · ref-top

Token-by-token explanation

  • <!-- — literal comment opening
  • [\s\S]*? — any characters including newlines, lazily (as few as possible)
  • --> — literal comment closing
  • g flag — find every comment

What it matches

<!-- note --><!-- multi line --><!-- a --><!-- b -->

What it does not match

<!-- unclosed<!- not a comment ->plain text

When to use it

Reach for a web pattern for quick scanning and lightweight transforms of markup, styling and web identifiers: locating tags, comments, colors, slugs or Markdown links. For anything structural or security-sensitive — parsing a DOM, sanitizing HTML, rewriting CSS — use a real parser or a proven library instead, because markup is not a regular language and regex-based handling is a frequent source of bugs and cross-site scripting bypasses.

Caveats

  • The lazy *? stops at the first -->, which is correct for well-formed comments but can mis-handle nested or malformed comment syntax.
  • [\s\S] is used instead of . because . does not match newlines without the s (dotAll) flag.
  • HTML comments cannot legally contain -- inside; real parsers enforce this, but the regex is permissive.

Code examples

JavaScript
const re = /<!--[\s\S]*?-->/g;
const text = "see <!-- note --> and more";
const found = [...text.matchAll(re)].map(m => m[1] ?? m[0]);
// found holds every extracted occurrence
Python
import re

rx = re.compile(r"<!--[\s\S]*?-->")
text = "see <!-- note --> and more"
found = rx.findall(text)   # every occurrence (groups if present)
Java
import java.util.regex.*;

Pattern p = Pattern.compile("<!--[\\s\\S]*?-->");
Matcher m = p.matcher("<!-- note -->");
boolean ok = m.find();   // scan for occurrences
PHP
<?php
$subject = "<!-- note -->";
if (preg_match_all('/<!--[\s\S]*?-->/', $subject, $m)) {
    // $m[0] is the full match; $m holds every occurrence
}

How to test it

Before trusting any pattern, test it against three kinds of input: valid examples that must match, invalid examples that must be rejected, and edge cases at the boundaries (empty strings, maximum lengths, unusual separators and Unicode). Paste the expression into a live regex tester with your actual sample data and confirm the highlighted matches are exactly what you intend. Watch for catastrophic backtracking by trying long non-matching inputs, and remember that engine differences (JavaScript, Python, Java, PCRE, Go/RE2) mean a pattern that works in one may fail or behave differently in another — especially lookarounds, which Go's RE2 does not support at all.

Frequently asked questions

Why use [\s\S] instead of .?

The dot does not match newline characters by default, so multi-line comments would be missed. [\s\S] matches any character including newlines; alternatively use the s (dotAll) flag with .*?.

Why a lazy quantifier?

The *? stops at the first --> rather than the last, so two separate comments are matched individually instead of as one giant span.

When should I avoid regex for web content?

For parsing HTML, CSS or Markdown structure, use a real parser. Regex cannot handle nesting, quoted delimiters or malformed markup reliably, and regex-based sanitization is a common source of XSS bypasses.

Why is regex HTML sanitization dangerous?

HTML has nested, quoted and malformed constructs that regex mis-parses, so attackers hide scripts in forms the pattern misses. Always sanitize with a proven library (DOMPurify) or a real parser, never ad-hoc regex.

Advertisement
Ad slot · ref-in-article

Try the Regex Tester

Live regex matching with groups, flags and explanations.

Open tool →