daisy
daisy

Reputation: 23511

Merge multiple regex, how can I know which part got matched?

Here's a minimal case,

I have multiple regex, that is aa, bb, and cc, in the old days, I just loop through all regex and see if the string can match any of those. If any regex got matched, stop the process.

But now I decided to put it altogether, with a simple OR operation, now I get

(aa)|(bb)|(cc)

So if I get a match, the $1 would be what I wanted, but I wouldn't be able to know if it's (aa) or (bb) or (cc) that did it, any ideas?

Upvotes: 1

Views: 71

Answers (1)

ysth
ysth

Reputation: 98398

In your example, if aa matched, $1 will be set; if bb matched, $1 will be undef and $2 will be set, etc.

if ( defined $1 ) {
    print "first part matched: $1.\n";
}
elsif ( defined $2 ) {
    print "second part matched: $2.\n";
}
...

or, more dynamically, using @- and @+:

my $string = "xbb";
if ( $string =~ /(aa)|(bb)|(cc)/ ) {
    my $match = ( grep defined $-[$_], 1..$#- )[0];
    if ( defined $match ) {
        print "part $match matched: " . substr( $string, $-[$match], $+[$match]-$-[$match] ) . ".\n";
    }
}

Upvotes: 3

Related Questions