3 ms·
Perl (5.18, at least) does let you (ab)use named groups to provide match-part identification. Given `(?<g1>Sat)urday|(?<g2>Sun)day`, and a successful match, ei
by zimpenfish 13y ago
Perl (5.18, at least) does let you (ab)use named groups to provide match-part identification.
Given `(?<g1>Sat)urday|(?<g2>Sun)day`, and a successful match, either `$+{g1}` or `$+{g2}` will hold the relevant subpart.
Quickie demo script:
my $re = "(?<g1>Sat)urday|(?<g2>Sun)day";
foreach my $d (qw(Friday Sunday Thursday Saturday)) {
my $out = '<default>';
if ($d =~ /$re/) {
if ($+{g1}) { $out = 'Saturday' }
elsif ($+{g2}) { $out = 'Sunday' }
}
print "$d routes to $out\n";
}
- BugBrother 13y agoNice to see code. :-) Perl 5.10 from 2007 supports named captures. (Google confirmed that.) Edit: nikic in the parallel comment is correct, named captures are affected the same way in Perl's regexp engine with ?|. (Google perlre and search for ?|.)
- nikic 13y agoNot sure I understand this comment. Your code snippet uses named subpatterns, but not within a (?| group. The interesting question is whether you can combined those two. Without (?| you can use named captures in PCRE as well (there's just little point in this context as a non-named capture would do equally well and be more efficient.)
- zimpenfish 13y agoOh, hmm, yeah, fair point. I was mistakenly assuming that using named captures would obviate the creation of N spurious capture groups but a quick benchmark proves that horribly wrong. Sorry all!