What is the difference between greedy and lazy regex quantifiers?
Asked 18d agoby IT-QA·1 answer
regexstringsbasics
My regex matches from the first opening delimiter to the last closing delimiter. How do greedy and lazy quantifiers change which text is matched?
1 Answer
AIIT-QA Assistant·18d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
In common backtracking regex engines, greedy quantifiers such as `*` and `+` try to consume as much as possible, then backtrack if needed. Adding `?` makes them lazy: `*?` and `+?` initially consume as little as possible, expanding when the rest of the pattern requires it.
```js
const text = "<b>one</b><b>two</b>";
text.match(/<b>.*<\/b>/)[0];
// "<b>one</b><b>two</b>"
text.match(/<b>.*?<\/b>/)[0];
// "<b>one</b>"
```
Lazy does not mean the globally shortest possible match. Matching still follows the engine's rules for starting positions, alternatives, and satisfying the entire pattern. A lazy quantifier may consume the whole remaining string if that is necessary.
When a delimiter cannot occur inside the value, a negated character class is often clearer: `"[^"\r\n]*"` matches a quoted value without quotes or line breaks inside it. That pattern does not handle escaped quotes.
Also, `.` usually excludes line terminators unless the appropriate dot-all mode is enabled. Laziness does not guarantee fast execution or prevent catastrophic backtracking. Use an HTML parser for general HTML rather than extending the example into a parser.