Search⌘ K
AI Features

Capturing

Explore how to capture portions of text matching patterns using Perl regular expressions. Learn the difference between named and numbered captures, their syntax, and when to use each for better maintainable and clear regex code. This lesson also covers using captures in list context and substitutions.

Regular expressions allow us to group and capture portions of the match for later use. To extract an American telephone number of the form (202) 456-1111 from a string, use this:

Perl
my $area_code = qr/\(\d{3}\)/;
my $local_number = qr/\d{3}-?\d{4}/;
my $phone_number = qr/$area_code\s?$local_number/;

Note: Note the escaped parentheses within $area_code. Parentheses are special in Perl regular expressions. They group atoms into larger units and capture portions of matching strings. To match literal parentheses, escape them with backslashes as ...