← Back to Perl Course | Chapter 4: Regular Expressions | Lesson 3 of 7

Capturing groups

Parentheses save the part of the string they matched.

In this page:

  1. Capturing groups

Capturing groups

Each pair of parentheses in a pattern captures text into $1, $2 and so on, numbered by the position of the opening parenthesis. In list context, a successful match returns the captures as a list, which makes it easy to unpack them into variables. Named captures written (?<name>...) are stored in the %+ hash.

Note: The capture variables keep their values only until the next successful match, so copy them if you need them later.

Example: Capturing groups

perl
use strict;
use warnings;

my $date = "Released on 2019-12-25.";
if ($date =~ /(\d{4})-(\d{2})-(\d{2})/) {
    print "year=$1 month=$2 day=$3\n";
}
my ($user, $domain) = "alice\@example.com" =~ /^(\w+)@([\w.]+)$/;
print "user=$user domain=$domain\n";
if ("John Smith" =~ /(?<first>\w+)\s+(?<last>\w+)/) {
    print "last name: $+{last}, first name: $+{first}\n";
}
if ("abc" =~ /(a)(b)?(x)?/) {
    print "group 3 is ", defined $3 ? "defined" : "undef", "\n";
}

# Output:
# year=2019 month=12 day=25
# user=alice domain=example.com
# last name: Smith, first name: John
# group 3 is undef
Common Mistakes
  1. Using $1 after a failed match and expecting the old value
  2. Mixing up the numbering of nested groups
  3. Forgetting to check that the match succeeded before using $1
Chapter Summary
  • Parentheses capture into $1, $2 ...
  • List context returns the captures
  • (?<name>...) stores into %+
  • Only use captures after a successful match
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.