Learn regular expressions · Lesson 10

Greedy and lazy

Quantifiers are greedy: they take as much as they can. Usually that’s what you want, until .* meets a text with more than one of what ends it. Here the pattern is meant to find each quoted word:

/".*"/g1 match
She said "yes" and then "no".
Try it in Dotstar →

One match, from the first quote to the last: .* took everything up to the end of the line, then gave back characters one at a time until a " could follow, and the last " was the first it found on the way back.

Lazy: *? and +?

A ? after a quantifier makes it lazy: it takes as little as it can, and more only when the rest of the pattern can’t match yet.

/".*?"/g2 matches
She said "yes" and then "no".
Try it in Dotstar →

Each quantifier has a lazy form: *?, +?, ?? and {n,m}?. Lazy doesn’t mean shorter in every case, only that it tries fewer repetitions first: the match still starts at the leftmost place it can.

Often better: say what can’t be inside

A negated class says it more exactly: a quote, anything but a quote, a quote.

/"[^"]*"/g2 matches
She said "yes" and then "no".
Try it in Dotstar →

It can’t run past a closing quote whatever comes after, and it doesn’t try and retry the way .*? does, so on long texts it’s also faster. When what ends a part is a single character, a negated class is usually the best way to write it.