regex intermediate

How to use named capture groups in Perl regex

Question

How do I use named capture groups in Perl regular expressions?

Named capture groups use the (?<name>pattern) syntax and can be accessed via the %+ hash:

use v5.10;
use strict;
use warnings;

my $text = "John Doe, age 30";

if ($text =~ /(?<first>\w+)\s+(?<last>\w+),\s+age\s+(?<age>\d+)/) {
    say "First name: $+{first}";
    say "Last name: $+{last}";
    say "Age: $+{age}";
}

# Output:
# First name: John
# Last name: Doe
# Age: 30

# You can also use numbered captures
say "Full match: $&";
say "First capture: $1";  # Also contains 'John'

Named captures make regex more readable and maintainable, especially for complex patterns.

Was this helpful?

Related Questions