Lazy and greedy quantifiers in regular expressions
Published on in Regular expressions
Last updated on
Greedy quantifiers (the default, e.g.
*) match as much as possible.
Lazy quantifiers (e.g.
*?) match as little as possible.
Table of contents
Greedy quantifiers keep looking until the condition is not satisfied. They match as much as possible.
Quantifiers are greedy by default.
Lazy quantifiers stop looking when the condition is satisfied. They match as little as possible.
Quantifiers can be made lazy by appending a question mark.
|Greedy quantifier||Lazy quantifier||Description|
||zero or more|
||one or more|
||zero or one|
||n or more|
||between n and m|
const html = '<div>foo</div>' // Greedy html.match(/<.+>/) //=> '<div>foo</div>' // Lazy html.match(/<.+?>/) //=> '<div>'
As you can see, the greedy quantifier is too greedy in this case, whereas the lazy quantifier matches just enough but not too much. It's like smart laziness. Nice!
Sometimes an alternative is to use a negated character class:
html.match(/<[^>]+>/) //=> '<div>'
In this case the result is the same as when using the lazy quantifier, but the performance is better because "the negated character class can only match one way for a given input."