Lazy / Non-Greedy Quantifier
Demonstrate lazy quantifiers `+?` by matching the SHORTEST HTML-like tag rather than the longest greedy span.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("<.+?>", "g");
const input = "<b>bold</b> and <i>italic</i>";
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"<.+?>")
input_text = "<b>bold</b> and <i>italic</i>"
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(`<.+?>`)
input := `<b>bold</b> and <i>italic</i>`
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
<.+?> (flags: g)Raw source: <.+?>
How it works
Examples
Input
<b>bold</b> and <i>italic</i>Matches
<b></b><i></i>
Input
<div class="foo">x</div>Matches
<div class="foo"></div>
Input
no tagsNo match
—Common use cases
- •Pulling HTML/XML tags out of a stream
- •Stripping markup with String.replace
- •Demonstrating greedy-vs-lazy in tutorials
- •Quick parsers (use a real parser for prod)
Related patterns
Non-ASCII Character
Text ProcessingMatch runs of non-ASCII characters (anything outside U+0000–U+007F).
Non-Capturing Group (Image URL)
Text ProcessingUse non-capturing groups `(?:...)` to alternate without polluting the captured-groups list.
HCL / Terraform Variable Reference
Text ProcessingMatch Terraform / HCL references like `var.name`, `local.foo`, `module.x.output`, or `data.aws_ami.ubuntu.id`.
Keep-a-Changelog Entry Header
Text ProcessingMatch Keep-a-Changelog style version headers like `## [1.2.3] - 2024-01-15` or `## 2.0.0`.