Start free · Free tools · Fair usage limits
Browse Tools

Categories

Custom AI Solutions – AI2Flows
LIVE NEWS
Loading latest AI & SEO news…
Home›Tools›Regex Tester›Regex: HTML comments
Regex pattern · find & extract

Regex: HTML comments

Regex for HTML comments: a tested pattern with examples, a plain-English breakdown, and code for JavaScript, Python, PHP, Java and Go.

Quick answer

Use /<!--[\s\S]*?-->/g with the global flag to find every match. In "<p>A</p><!-- note --><p>B</p><!-- multi -->" it finds "<!-- note -->", "<!-- multi -->". The lazy *? stops at the first -->, so two comments are matched separately instead of as one big block.

Last updated · Maintained by FreeAIToolz · How we test

/<!--[\s\S]*?-->/g

2 match(es)

<p>A</p><!-- note --><p>B</p><!-- multi -->
Open in the full Regex Tester (replace, flags, groups) →

How this regex works

PartMeaning
<!--comment start
[\s\S]*?any characters, including newlines, as few as possible
-->comment end

Flags: g finds every match instead of stopping at the first.

Examples

InputMatches
<p>A</p><!-- note --><p>B</p><!-- multi --><!-- note -->, <!-- multi -->

Every example above is checked automatically in JavaScript and Python each time the site is built.

Limitations and edge cases

The lazy *? stops at the first -->, so two comments are matched separately instead of as one big block.

When to use this pattern

Removing comments from HTML templates and email builds.

Use it in your language

JavaScript

const matches = text.match(/<!--[\s\S]*?-->/g) ?? [];

Python

import re
matches = [m.group(0) for m in re.finditer(r'<!--[\s\S]*?-->', text)]

PHP

preg_match_all('~<!--[\\s\\S]*?-->~', $text, $m);
$matches = $m[0];

Java

Matcher m = Pattern.compile("<!--[\\s\\S]*?-->").matcher(text);
while (m.find()) { System.out.println(m.group()); }

Go

re := regexp.MustCompile(`<!--[\s\S]*?-->`)
matches := re.FindAllString(text, -1)

More regex patterns

Frequently asked questions

What is the regex for HTML comments?
/<!--[\s\S]*?-->/g. The lazy *? stops at the first -->, so two comments are matched separately instead of as one big block.
Which languages does this pattern work in?
It is tested in JavaScript and Python and uses syntax that also works in PHP (PCRE) and Java. It also works in Go’s RE2 engine.
How do I replace the matches?
In JavaScript use text.replace(/<!--[\s\S]*?-->/g, "replacement"); in Python use re.sub(r'<!--[\s\S]*?-->', "replacement", text).