regex-codicioso-no-codicioso

Greedy and Non-Greedy Quantifiers in Regex

  • 1 min

By default, quantifiers in Regex are greedy, meaning they will try to match the greatest possible number of repetitions within the text string.

However, sometimes we need the pattern to be more conservative and match the smallest possible amount of characters. For this, we use non-greedy (lazy) quantifiers.

Greedy Quantifiers

The quantifiers we have seen so far (*, +, {n,m}) are greedy and try to capture the maximum number of matches possible.

For example, this regular expression

start.*end
Copied!

This pattern will try to capture all the content up to the last end it finds. Let’s test it.

inicio contenido en medio fin fin fin otra cosa

Non-Greedy Quantifiers

To make a quantifier non-greedy, we add a ? after the quantifier. This way, it will search for the smallest possible number of matches.

For example, if we change the regular expression by adding ? to the * quantifier

start.*?end
Copied!

This pattern will try to capture the content up to the first end it finds. Let’s test it.

inicio contenido en medio fin fin fin otra cosa