Script Valley
Regex: Actually Useful Patterns
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

Lazy quantifiers

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.

Up next

Negated character class vs lazy quantifier which to use

Sign in to track progress

Lazy quantifiers in regex with question mark suffix โ€” Quantifiers and Greedy vs Lazy Matching โ€” Regex: Actually Useful Patterns โ€” Script Valley โ€” Script Valley