Quantifiers and Greedy vs Lazy MatchingLesson 4.2
Lazy quantifiers in regex with question mark suffix
lazy quantifier syntax, star question, plus question, lazy vs greedy comparison, HTML tag matching fix
Lazy: Match As Little As Possible
Append ? to any quantifier to make it lazy: *? +? {n,m}?. The engine now expands only as far as needed for the pattern to succeed.
// Lazy: stops at FIRST closing >
'<b>bold</b> and <i>italic</i>'.match(/<.+?>/g)
// => ['<b>', '</b>', '<i>', '</i>']
// Extract individual quoted strings
'"hello" and "world"'.match(/".*?"/g)
// => ['"hello"', '"world"']
Do not default to lazy. Use it specifically when you need the shortest balanced delimited match.
