Script Valley
Regex: Actually Useful Patterns
Quantifiers and Greedy vs Lazy MatchingLesson 4.1

Greedy quantifiers and why they over-match

greedy default behavior, star plus greedy, over-matching HTML, match expansion, how greedy backtrack works

Greedy Means Take As Much As Possible

Greedy matching

All quantifiers (* + {n,m}) are greedy by default: they match as many characters as possible while still allowing the overall pattern to succeed.

// Greedy: matches from first < to LAST >
'<b>bold</b> and <i>italic</i>'.match(/<.+>/)
// => ['<b>bold</b> and <i>italic</i>']

Greediness is correct when you want the longest match. It causes bugs when you expect to match the shortest balanced construct.

Up next

Lazy quantifiers in regex with question mark suffix

Sign in to track progress

Greedy quantifiers and why they over-match โ€” Quantifiers and Greedy vs Lazy Matching โ€” Regex: Actually Useful Patterns โ€” Script Valley โ€” Script Valley