Capturing groups
Parentheses save the part of the string they matched.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Using $1 after a failed match and expecting the old value
- Mixing up the numbering of nested groups
- 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: