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
- How to validate email addresses using Perl regex?
- How to split a string by regex pattern in Perl?
- How to use greedy vs non-greedy quantifiers in Perl regex?
- How to match start and end of string with ^ and $ in Perl?
- How to use alternation | in Perl regex?
- How to use the qr// operator to compile regex in Perl?