Language: EN

regex-codicioso-no-codicioso

Greedy and Non-Greedy Quantifiers in Regex

By default, quantifiers in Regex are greedy, which means they will try to match the maximum number of repetitions within the text string.

However, sometimes we need the pattern to be more conservative and match the minimum number of characters. For this, we use non-greedy quantifiers.

Greedy Quantifiers

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

For example, this regular expression

start.*end

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

start content in the middle end end end something else

Non-Greedy Quantifiers

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

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

start.*?end

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

start content in the middle end end end something else