Dallaylaen has asked for the wisdom of the Perl Monks concerning the following question:
Suppose I have a set of regural expression, and I want to match a string against them all together and do something depending on which of those expressions did match.
If those are just words, life's easy: put them all in parentheses and see what's in $1 after match.
I think I can use named captures:
#!/usr/bin/perl -w use 5.010; # want named captures use strict; use warnings; my @reglist = ( qr/food?/, qr/b[a4]rd?/, qr/baz(o+ka)?/ ); my $i; # regex index my $giant_regex = join "|", map { $i++; "(?<r$i>$_)" } @reglist; $giant_regex = qr/($giant_regex)/; foreach (qw(foobarbaz football barcode none bazoooooka)) { $_ =~ m/$giant_regex/; my @match = keys %+; print "@match\n"; }
The above code sample works, but maybe there are simpler variants and/or variants compatible with older perls?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Find out which subpattern matched in regex
by hdb (Monsignor) on Jun 14, 2013 at 12:51 UTC | |
by Dallaylaen (Chaplain) on Jun 21, 2013 at 08:09 UTC | |
|
Re: Find out which subpattern matched in regex
by space_monk (Chaplain) on Jun 14, 2013 at 12:26 UTC | |
|
Re: Find out which subpattern matched in regex
by Anonymous Monk on Jun 14, 2013 at 12:37 UTC |