Greedy and non-greedy matching
By default quantifiers grab as much text as they can, and a question mark makes them take as little as possible.
In this page:
Greedy and non-greedy matching
Quantifiers such as * and + are greedy, so they match the longest possible string that still lets the whole pattern succeed. Adding a ? after a quantifier makes it non-greedy (lazy), so it stops at the earliest possible point. This difference matters when you extract text between two delimiters that appear several times.
Note:
A negated class such as [^"]* is often clearer and faster than a lazy .*? for text between quotes.
Example: Greedy and non-greedy matching
use strict;
use warnings;
my $html = "<b>bold</b> and <i>italic</i>";
my ($greedy) = $html =~ /<(.+)>/;
my ($lazy) = $html =~ /<(.+?)>/;
print "greedy: $greedy\n";
print "lazy: $lazy\n";
my @tags = $html =~ /<(\w+)>/g;
print "tags: @tags\n";
my $quoted = 'say "hi" and "bye"';
my @strings = $quoted =~ /"([^"]*)"/g;
print "quoted: @strings\n";
my ($first_word) = "aaa bbb" =~ /(a+?)/;
print "lazy a+?: $first_word\n";
# Output:
# greedy: b>bold</b> and <i>italic</i
# lazy: b
# tags: b i
# quoted: hi bye
# lazy a+?: a
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Using .* between delimiters and capturing far too much
- Forgetting the ? for lazy matching
- Assuming lazy quantifiers change which matches exist rather than which one is chosen first
Chapter Summary
- Greedy quantifiers match as much as possible
- Adding ? makes a quantifier lazy
- Lazy matching stops at the first delimiter
- [^x]* is a precise alternative
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: