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?
In reply to Find out which subpattern matched in regex by Dallaylaen
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |