Search⌘ K

Greediness

Explore how greedy quantifiers like + and * match as much input as possible, and how the ? modifier creates nongreedy matches. Understand their impact on regex matching behavior and when to apply each type for effective Perl text processing.

Greedy quantifiers

The + and * quantifiers are greedy: they try to match the input string as much as possible. This can be particularly pernicious. Consider a naïve use of the “zero or more non-newline characters” pattern of .*:

Perl
# a poor regex
my $hot_meal = qr/hot.*meal/;
say 'Found a hot meal!' if 'I have a hot meal' =~ $hot_meal;
say 'Found a hot meal!' if 'one-shot, piecemeal work!' =~ $hot_meal;

Greedy quantifiers start by matching everything at first. If that match doesn’t succeed, the regex engine will ...