ZetCode

Perl regex quantifiers

last modified November 25, 2026 Perl 5.44

A quantifier says how many times the preceding item may repeat. The item can be a single character, a character class or a group in parentheses. Quantifiers decide whether a pattern grabs too much, too little or the right amount of text, and they also decide how much work the regex engine does. This article starts with the basic quantifiers and continues with the greedy, lazy and possessive forms.

The basic quantifiers

Three quantifiers are written with a single character. ? means zero or one time, * means zero or more times and + means one or more times.

basic.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @words = qw(color colour colouur gogle google gooogle ac abc abbbc);

for my $word (@words) {
    my @found;

    push @found, 'colou?r' if $word =~ /^colou?r$/;
    push @found, 'go+gle'  if $word =~ /^go+gle$/;
    push @found, 'ab*c'    if $word =~ /^ab*c$/;

    printf "%-8s %s\n", $word, @found ? "@found" : '-';
}

The pattern colou?r makes the letter u optional, so it matches both spellings but not a doubled u. go+gle requires at least one o, while ab*c also accepts no b at all. The anchors ^ and $ make each pattern match the whole word.

$ perl basic.pl
color    colou?r
colour   colou?r
colouur  -
gogle    go+gle
google   go+gle
gooogle  go+gle
ac       ab*c
abc      ab*c
abbbc    ab*c

Counted repetition

Braces give the number of repetitions exactly. {n} means exactly n times, {n,} at least n times and {n,m} between n and m times. The basic quantifiers are shorthands: ? is {0,1}, * is {0,} and + is {1,}.

counted.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @codes = qw(811 04 81101 8110 12345678 2026-11-25 26-11-25 2026-1-25);

for my $code (@codes) {
    my $kind = $code =~ /^\d{5}$/              ? 'postal code'
             : $code =~ /^\d{2,4}$/            ? 'short number'
             : $code =~ /^\d{4}-\d{1,2}-\d{2}$/ ? 'date'
             : $code =~ /^\d{6,}$/             ? 'long number'
             :                                   'unknown';

    printf "%-11s %s\n", $code, $kind;
}

The program classifies strings with a chain of conditional operators. The first pattern that matches decides the kind. A five-digit string is a postal code, two to four digits form a short number, and six or more a long one. The date pattern requires a four-digit year and a two-digit day, but accepts a month with one or two digits.

$ perl counted.pl
811         short number
04          short number
81101       postal code
8110        short number
12345678    long number
2026-11-25  date
26-11-25    unknown
2026-1-25   date

Greedy matching

All quantifiers shown so far are greedy. They match as much text as possible and give back characters only when the rest of the pattern would fail otherwise. This is often surprising.

greedy.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $html = '<b>bold</b> and <b>more bold</b>';

if ($html =~ /<b>(.*)<\/b>/) {
    say "captured: $1";
}

The intent is to capture the text of the first bold element. However, .* first runs to the end of the string. Then the engine backtracks: it gives back characters one by one until </b> can match. The first place where that succeeds, counting from the end, is the last closing tag. The capture therefore spans both elements.

$ perl greedy.pl
captured: bold</b> and <b>more bold

Lazy quantifiers

A question mark after a quantifier makes it lazy. A lazy quantifier matches as little as possible and takes more characters only when the rest of the pattern fails. Every quantifier has a lazy form: *?, +?, ?? and {n,m}?.

lazy.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $html = '<b>bold</b> and <b>more bold</b>';

if ($html =~ /<b>(.*?)<\/b>/) {
    say "first: $1";
}

my @all = $html =~ /<b>(.*?)<\/b>/g;
say "all:   ", join ' | ', @all;

my $digits = '2026';
my ($two) = $digits =~ /(\d{2,4}?)/;
say "lazy {2,4}?: $two";

With .*?, the engine tries the shortest possible text first and stops at the first closing tag. With the /g modifier in list context, the pattern finds the text of both elements. The lazy {2,4}? takes only two digits, the minimum, because nothing after it requires more.

$ perl lazy.pl
first: bold
all:   bold | more bold
lazy {2,4}?: 20

Negated character classes

For text between delimiters, there is a better tool than a lazy quantifier. A negated character class such as [^"]* matches any characters except the closing delimiter, so it cannot run past it.

negated.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $line = 'name="Lucia" city="Bratislava" role="admin"';

my @lazy = $line =~ /(\w+)="(.*?)"/g;
say "lazy:    @lazy";

my @negated = $line =~ /(\w+)="([^"]*)"/g;
say "negated: @negated";

my $config = 'path=/usr/local/bin;mode=fast;';
my @parts = $config =~ /(\w+)=([^;]*);/g;
say "parts:   @parts";

For the attribute list, both patterns find the same pairs. The difference is in how they get there. The lazy .*? tries to end the match after every character, while [^"]* consumes the whole value in one go and never backtracks. It also states the intent more clearly. The same technique splits the configuration string at the semicolons.

$ perl negated.pl
lazy:    name Lucia city Bratislava role admin
negated: name Lucia city Bratislava role admin
parts:   path /usr/local/bin mode fast

Quoted strings with escapes

Neither form works when the value itself may contain an escaped delimiter, such as \". The pattern must then treat a backslash and the character after it as a single unit.

quoted.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $line = 'name="Lucia" note="say \"hi\"" city="Bratislava"';

my @lazy = $line =~ /(\w+)="(.*?)"/g;
say "lazy:    ", join ' | ', @lazy;

my @escaped = $line =~ /(\w+)="((?:[^"\\]|\\.)*)"/g;
say "escaped: ", join ' | ', @escaped;

for my $value (@escaped[1, 3, 5]) {
    (my $clean = $value) =~ s/\\(.)/$1/g;
    say "value: $clean";
}

The lazy pattern stops at the escaped quote and breaks the rest of the line into wrong pieces. The group (?:[^"\\]|\\.)* repeats one of two alternatives: a character that is neither a quote nor a backslash, or a backslash followed by any character. An escaped quote is consumed by the second alternative, so it does not end the value. Finally, a substitution removes the backslashes from the values.

$ perl quoted.pl
lazy:    name | Lucia | note | say \ | city | Bratislava
escaped: name | Lucia | note | say \"hi\" | city | Bratislava
value: Lucia
value: say "hi"
value: Bratislava

Possessive quantifiers and atomic groups

A possessive quantifier, written with a trailing plus such as a++ or [^"]*+, matches as much as it can and never gives anything back. An atomic group (?>...) does the same for a whole subpattern. Once it has matched, the engine does not backtrack into it.

possessive.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $s = 'aaab';

for my $re (qr/^a+ab$/, qr/^a++ab$/, qr/^(?>a+)ab$/) {
    my $result = $s =~ $re ? 'match' : 'no match';
    printf "%-16s %s\n", $re, $result;
}

my $csv = '"one","two","three"';
my @items = $csv =~ /"([^"]*+)"/g;
say "items: @items";

my $id = 'user12345x';
say "digits: $1" if $id =~ /^[a-z]++(\d++)[a-z]$/;

In ^a+ab$, the plain a+ first takes all three letters, then gives one back so that the following a can match. The possessive and atomic forms keep all three letters, the rest of the pattern cannot match, and the match fails. The stringified patterns show the flags that qr adds.

When giving back could never lead to a match, a possessive quantifier changes nothing in the result. It only saves useless work. That is the case in the last two matches, where the quantified items cannot match the character that follows them.

$ perl possessive.pl
(?^u:^a+ab$)     match
(?^u:^a++ab$)    no match
(?^u:^(?>a+)ab$) no match
items: one two three
digits: 12345

Runaway backtracking

A nested quantifier such as (a+)+ can split a run of letters between the inner and the outer quantifier in a huge number of ways. When the match fails, a backtracking engine may try all of them. Perl remembers failed positions and avoids most of these cases, but some features, such as backreferences, turn this protection off.

backtrack.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Time::HiRes qw(time);

my $nested = qr/^(a+)+\1b/;
my $atomic = qr/^(?>(a+)+)\1b/;

say "length  nested    atomic";

for my $n (16, 18, 20, 22, 24) {
    my $text = 'a' x $n . '!';

    my $start = time;
    $text =~ $nested;
    my $t1 = time - $start;

    $start = time;
    $text =~ $atomic;
    my $t2 = time - $start;

    printf "%-6d  %.4f s  %.4f s\n", $n, $t1, $t2;
}

Both patterns fail, because the text ends with an exclamation mark. The nested pattern needs about four times longer with every two added letters, so one more step in the table would take seconds. In the atomic version, the group (?>(a+)+) takes all letters once and does not try other splits. The times depend on the machine, but the growth does not.

$ perl backtrack.pl
length  nested    atomic
16      0.0063 s  0.0000 s
18      0.0197 s  0.0000 s
20      0.0781 s  0.0000 s
22      0.3593 s  0.0000 s
24      1.1870 s  0.0000 s

Best practices

The following guidelines help when working with regex quantifiers.

Source

perlre: Quantifiers ยท perlretut

In this article we have covered the basic quantifiers, counted repetition, greedy and lazy matching, negated character classes, escaped delimiters, possessive quantifiers, atomic groups and runaway backtracking. See also Perl regex, Perl global matching and Perl lookaround.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Perl tutorials.