TExcelTAD
Home › Perl › Captures and Named Captures

Captures and Named Captures

Knowing that a pattern matched is useful; extracting what it matched is even more useful. Parentheses in a regex create capture groups, and the text they matched is saved for you.

Numbered captures: $1, $2, ...

After a successful match, the first group's text is in $1, the second in $2, and so on, counting opening parentheses from the left:

perl · try it yourself
use strict;
use warnings;

my $date = "Released on 2024-03-15.";

if ($date =~ /(\d{4})-(\d\d)-(\d\d)/) {
    print "Year: $1, month: $2, day: $3\n";
    print "Whole match: 
amp;\n"; }
Year: 2024, month: 03, day: 15
Whole match: 2024-03-15

amp; holds the entire matched text. Since Perl 5.20 it no longer slows programs down, but many people prefer to capture explicitly.

Warning: $1 and friends keep their values from the last successful match. Always use them inside an if that checks the match, or a failed match will leave you reading stale data.

Captures in list context

A match in list context returns the captured groups directly. This is usually the cleanest style:

perl · try it yourself
use strict;
use warnings;

my $line = "user=maria id=1042 role=admin";

my ($user, $id) = $line =~ /user=(\w+) id=(\d+)/;
print "User $user has id $id\n";

my ($missing) = $line =~ /email=(\S+)/;
print "Email: ", $missing // "none", "\n";

my %fields = $line =~ /(\w+)=(\S+)/g;
print join(", ", map { "$_ => $fields{$_}" } sort keys %fields), "\n";
User maria has id 1042
Email: none
id => 1042, role => admin, user => maria

With /g and two groups, the match returns key, value, key, value... which can be assigned straight to a hash.

Named captures

Numbered groups get confusing in long patterns. Named captures (?<name>...) store the text in the special hash %+:

perl · try it yourself
use strict;
use warnings;

my @entries = (
    "2024-05-01 10:15:02 WARN  Disk usage at 85%",
    "2024-05-01 10:16:40 ERROR Database connection lost",
);

for my $entry (@entries) {
    if ($entry =~ /^(?<date>\S+) (?<time>\S+) (?<level>\w+)\s+(?<msg>.*)$/) {
        print "[$+{level}] at $+{time}: $+{msg}\n";
    }
}
[WARN] at 10:15:02: Disk usage at 85%
[ERROR] at 10:16:40: Database connection lost

The names document what each part means, and adding a new group does not renumber the others.

Non-capturing groups

Sometimes you need parentheses only for grouping, for example around an alternation. (?:...) groups without capturing, so your numbering stays simple:

perl · try it yourself
use strict;
use warnings;

for my $size ("12px", "1.5em", "80%", "3pt") {
    if ($size =~ /^([\d.]+)(?:px|em|%)$/) {
        print "$size -> number $1\n";
    } else {
        print "$size -> unsupported unit\n";
    }
}
12px -> number 12
1.5em -> number 1.5
80% -> number 80
3pt -> unsupported unit

Backreferences

Inside the pattern itself, \1 (or \g1, or \k<name>) refers back to what a group matched earlier in the same match. That finds repeated text:

perl · try it yourself
use strict;
use warnings;

my $text = "This is is a test of the the backreference";
my @doubles = $text =~ /\b(\w+) \1\b/g;
print "Repeated words: @doubles\n";

for my $word (qw(level noon apple abba)) {
    my $kind = $word =~ /^(.)(.).?\2\1$/ ? "4-5 letter palindrome" : "-";
    print "$word: $kind\n";
}
Repeated words: is the
level: 4-5 letter palindrome
noon: 4-5 letter palindrome
apple: -
abba: 4-5 letter palindrome

Looping over all matches

In scalar context, /g finds one match per call and remembers where it stopped, so a while loop walks through every match along with its captures:

perl · try it yourself
use strict;
use warnings;

my $prices = "apple 1.20, bread 2.75, milk 0.99";
my $total = 0;

while ($prices =~ /(\w+) (\d+\.\d+)/g) {
    print "Item: $1 costs $2\n";
    $total += $2;
}
printf "Total: %.2f\n", $total;
Item: apple costs 1.20
Item: bread costs 2.75
Item: milk costs 0.99
Total: 4.94

Test yourself

After "ab12" =~ /([a-z]+)(\d+)/, what is $2?

  1. ab
  2. 12
  3. ab12
  4. undef

Where are named captures like (?<year>\d{4}) stored?

  1. $year
  2. @-
  3. $+{year}
  4. %ENV

What does (?:...) do?

  1. Makes a group optional
  2. Groups without capturing
  3. Creates a named capture
  4. Negates the group