Minimal match

2 snippets in Regular Expressions

RXRegular Expressions

Greedy vs Lazy Matching

RX · Quantifiers
Syntax
Greedy: .*  .+  .?     Lazy: .*?  .+?  .??
Example
JS:  '<b>bold</b> and <b>more</b>'.match(/<b>.*<\/b>/)
JS:  '<b>bold</b> and <b>more</b>'.match(/<b>.*?<\/b>/)
Output
Greedy: "<b>bold</b> and <b>more</b>"  (longest match)
Lazy:   "<b>bold</b>"  (shortest match)

Note Greedy quantifiers eat as much as possible, then backtrack. Lazy quantifiers match as little as possible, then expand. This distinction is critical when parsing HTML, quoted strings, or any delimited content. Always prefer lazy when you want the nearest closing delimiter.

Non-Greedy Scanning Patterns

RX · Advanced Techniques
Syntax
.*?target  (scan forward minimally until target is found)
Example
JS:  'START data1 END noise START data2 END'.match(/START(.*?)END/g)
Py:  re.findall(r'START(.*?)END', 'START data1 END noise START data2 END')
Output
JS: ["START data1 END", "START data2 END"]
Py: [" data1 ", " data2 "]  (findall returns groups)

Note The .*? idiom scans forward character by character until the following pattern matches. This is the standard approach for extracting content between delimiters. Be aware that .*? can still cause slowdowns on long strings with no match -- consider using negated character classes instead when possible.

Frequently asked questions

How does Regular Expressions handle minimal match?
Regular Expressions covers this with 2 copy-ready snippets on this page. The "Greedy vs Lazy Matching" snippet in Regular Expressions uses `Greedy: .* .+ .? Lazy: .*? .+? .??`.
Which pattern does the Regular Expressions example use?
The "Greedy vs Lazy Matching" snippet uses `Greedy: .* .+ .? Lazy: .*? .+? .??`, from the Quantifiers section of the Regular Expressions cheat sheet.
What other Regular Expressions snippets are shown for "minimal match"?
Besides "Greedy vs Lazy Matching", this page also shows "Non-Greedy Scanning Patterns".
Is there anything to watch out for?
Yes. For "Greedy vs Lazy Matching": Greedy quantifiers eat as much as possible, then backtrack. Lazy quantifiers match as little as possible, then expand. This distinction is critical when parsing HTML, quoted strings, or any delimited content. Always prefer lazy when you want the nearest closing delimiter.