Parentheses capture parts of a regex match so the program can use them later.

capture group A capture group stores the text matched by a parenthesized part of a regex.

Capture Groups

code
capture_groups.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;

my $code = "PR-204";
my $matched = $code =~ /^([A-Z]+)-(\d+)$/;
my $prefix = $matched ? $1 : "none";
my $number = $matched ? $2 : "none";

print "code=$code\n";
print "prefix=$prefix\n";
print "number=$number\n";
use strict;
use warnings;

my $code = "QA-7";
my $matched = $code =~ /^([A-Z]+)-(\d+)$/;
my $prefix = $matched ? $1 : "none";
my $number = $matched ? $2 : "none";

print "code=$code\n";
print "prefix=$prefix\n";
print "number=$number\n";
use strict;
use warnings;

my $code = "bad";
my $matched = $code =~ /^([A-Z]+)-(\d+)$/;
my $prefix = $matched ? $1 : "none";
my $number = $matched ? $2 : "none";

print "code=$code\n";
print "prefix=$prefix\n";
print "number=$number\n";
  1. $code ← PR-204, $matched ← 1, $prefix ← PR, $number ← 204

    4my $code→ PR-204 = "PR-204"; #@code="QA-7", "bad"5my $matched→ 1 = $codePR-204 =~ /^([A-Z]+)-(\d+)$/;6my $prefix→ PR = $matched1 ? $1 : "none";7my $number→ 204 = $matched1 ? $2 : "none";89print "code=$codePR-204\n";10print "prefix=$prefixPR\n";11print "number=$number204\n";
    outputcode=PR-204
    prefix=PR
    number=204
  1. $code ← QA-7, $matched ← 1, $prefix ← QA, $number ← 7

    4my $code→ QA-7 = "QA-7";5my $matched→ 1 = $codeQA-7 =~ /^([A-Z]+)-(\d+)$/;6my $prefix→ QA = $matched1 ? $1 : "none";7my $number→ 7 = $matched1 ? $2 : "none";89print "code=$codeQA-7\n";10print "prefix=$prefixQA\n";11print "number=$number7\n";
    outputcode=QA-7
    prefix=QA
    number=7
  1. $code ← bad, $matched ← (empty), $prefix ← none, $number ← none

    4my $code→ bad = "bad";5my $matched→ (empty) = $codebad =~ /^([A-Z]+)-(\d+)$/;6my $prefix→ none = $matched(empty) ? $1 : "none";7my $number→ none = $matched(empty) ? $2 : "none";89print "code=$codebad\n";10print "prefix=$prefixnone\n";11print "number=$numbernone\n";
    outputcode=bad
    prefix=none
    number=none

Follow the Captures

  1. $code starts as PR-204.
  2. The regex expects uppercase letters, a dash, and digits.
  3. PR fills the first capture group.
  4. 204 fills the second capture group.
  5. The program prints prefix=PR and number=204. | code | prefix | number | | --- | --- | --- | | PR-204 | PR | 204 | | QA-7 | QA | 7 | | bad | none | none |

Exercise: capture_groups.pl

Reproduce code=PR-204, prefix=PR, and number=204, then use the pinned code variants QA-7 and bad to predict prefix=QA number=7 and prefix=none number=none.