HTML Comment
Match HTML comments, including multi-line comments and empty ones.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("<!--[\\s\\S]*?-->", "g");
const input = "<!-- hello -->";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
import re
pattern = re.compile(r"<!--[\s\S]*?-->")
input_text = "<!-- hello -->"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Go (RE2) code
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`<!--[\s\S]*?-->`)
input := `<!-- hello -->`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
Pattern
<!--[\s\S]*?--> (flags: g)Raw source: <!--[\s\S]*?-->
How it works
Examples
Input
<!-- hello -->Matches
<!-- hello -->
Input
<p>keep</p><!-- remove --><span>keep</span>Matches
<!-- remove -->
Input
no comments hereNo match
—Common use cases
- •Stripping comments from HTML output
- •Build-time template cleanup
- •Detecting conditional IE comments
- •Static site generator preprocessing
Related patterns
HTML Attribute
WebMatch HTML attributes of the form name="value" or name='value' and capture both parts.
HTML Entity
WebMatch HTML entities in named (`&`), numeric (`{`), or hex (`💩`) form.
HTML Tag Matcher
WebMatch paired HTML tags and capture the tag name and inner content using a back-reference.
CSS Class from `class=""` Attribute
WebExtract the value of a `class="..."` attribute from raw HTML, handling double or single quotes.
Related concepts
Lazy vs. Greedy Quantifiers
ConceptGreedy quantifiers (*, +) consume as much as possible before backtracking. Lazy quantifiers (*?, +?) consume as little as possible.
Regex Flags in JavaScript: g, i, m, s, u, y
ConceptFlags modify regex behavior globally. g enables global matching, i makes it case-insensitive, m changes anchor behavior, s dots match newlines, u enables Unicode, y is sticky.
How to Match Across Newlines in JavaScript
How-toThe dot doesn't match newlines by default. Use the s (dotall) flag, or build an explicit [\s\S] alternative for engines that predate s.