Advanced Regular Expression Patterns
Named Captures
Named captures make a match easier to read when several pieces are extracted.
named-captures
Named captures keep the extracted fields tied to their meaning instead of only their position in the pattern.
Named Captures
named_captures.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;
my $code = "ticket-42";
my $matched = $code =~ /^(?<kind>[a-z]+)-(?<id>\d+)$/;
my $kind = $matched ? $+{kind} : "none";
my $id = $matched ? $+{id} : "none";
print "code=$code\n";
print "matched=$matched\n";
print "kind=$kind\n";
print "id=$id\n";
use strict;
use warnings;
my $code = "bug-7";
my $matched = $code =~ /^(?<kind>[a-z]+)-(?<id>\d+)$/;
my $kind = $matched ? $+{kind} : "none";
my $id = $matched ? $+{id} : "none";
print "code=$code\n";
print "matched=$matched\n";
print "kind=$kind\n";
print "id=$id\n";
use strict;
use warnings;
my $code = "bad";
my $matched = $code =~ /^(?<kind>[a-z]+)-(?<id>\d+)$/;
my $kind = $matched ? $+{kind} : "none";
my $id = $matched ? $+{id} : "none";
print "code=$code\n";
print "matched=$matched\n";
print "kind=$kind\n";
print "id=$id\n";
$code ← ticket-42, $matched ← 1, $kind ← ticket, $id ← 42
4my $code→ ticket-42 = "ticket-42"; #@code="bug-7", "bad"5my $matched→ 1 = $codeticket-42 =~ /^(?<kind>[a-z]+)-(?<id>\d+)$/;6my $kind→ ticket = $matched1 ? $+{kind} : "none";7my $id→ 42 = $matched1 ? $+{id} : "none";89print "code=$codeticket-42\n";10print "matched=$matched1\n";11print "kind=$kindticket\n";12print "id=$id42\n";outputcode=ticket-42 matched=1 kind=ticket id=42
$code ← bug-7, $matched ← 1, $kind ← bug, $id ← 7
4my $code→ bug-7 = "bug-7";5my $matched→ 1 = $codebug-7 =~ /^(?<kind>[a-z]+)-(?<id>\d+)$/;6my $kind→ bug = $matched1 ? $+{kind} : "none";7my $id→ 7 = $matched1 ? $+{id} : "none";89print "code=$codebug-7\n";10print "matched=$matched1\n";11print "kind=$kindbug\n";12print "id=$id7\n";outputcode=bug-7 matched=1 kind=bug id=7
$code ← bad, $matched ← (empty), $kind ← none, $id ← none
4my $code→ bad = "bad";5my $matched→ (empty) = $codebad =~ /^(?<kind>[a-z]+)-(?<id>\d+)$/;6my $kind→ none = $matched(empty) ? $+{kind} : "none";7my $id→ none = $matched(empty) ? $+{id} : "none";89print "code=$codebad\n";10print "matched=$matched(empty)\n";11print "kind=$kindnone\n";12print "id=$idnone\n";outputcode=bad matched= kind=none id=none