DavidSzczesniak
12/20/2017 - 10:52 AM

Capturing

Regular expressions allow you to group and capture portions of the match for later use.

\!h # Example - extract an American telephone number of the form (202)456-1111:
my $area_code = qr/\(\d{3)\)/; # escaped parentheses
my $local_number = qr /\d {3}-?\d{4}/;
my $phone_number = qr/$area\s?$local_number/;

\!h # Named captures - capture portions of matches from applying a regex and access them later.
# Example - extracting a phone number from contact information:
if ($contact_info =~ /(?<phone>$phone_number)/) {
  say "Found a number $+{phone}";
}

# Named capture syntax: 
(?<capture name> ...)
# the ?<name> construct immediately follows the opening parentheses and provides a name for this particular capture
# the rest of the capture is the regular expression

\!h # Numbered Captures 
if ($contact_info =~ /($phone_number)/) {
  say "Found a number $1";
}
# Perl stores the captured substring in a series of magic variables. 
# The first matching capture goes into $1, the second into $2, and so on.