Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Matching against list of patterns

by hv (Parson)
on Sep 16, 2004 at 14:07 UTC ( #391451=note: print w/ replies, xml ) Need Help??


in reply to Matching against list of patterns

There are a couple of ways to discover what pattern matched. The easiest is probably to use backrefs:

my $pattern = join '|', map "($_)", @patterns; ... if ($line =~ /$pattern/i) { my $matchref = $#-; print "matched $pattern[$matchref - 1]\n"; }

As warned by other posters, you may need to play with the ordering to ensure that the preferred pattern matches if more than one can, in which case you will also need a way to get back from the index of the matched backreference to the actual pattern.

Hugo


Comment on Re: Matching against list of patterns
Download Code
Re^2: Matching against list of patterns
by Schuk (Pilgrim) on Nov 17, 2004 at 12:42 UTC
    To get the matched pattern matched text you can simply do:
    my $pattern = join '|', map "($_)", @patterns; ... if ($line =~ /($pattern)/i) { print "matched $1\n"; }
    But be carefull if you want to get another matched text in this line. Somewhat it eats up all $1,$2,$3. Use $+ to get the last matched text of the line.

    Schuk

    Edit: Sorry HV I should learn to read more carefully.

      That shows you what text matched, not which pattern matched it.

      There's nothing wrong with it as a way of finding out what text matched, but in the node you replied to I was specifically trying to address this aspect of the root node: the whole point of this excercise is to figure out WHICH regexp matched.

      Hugo

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://391451]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2014-12-20 21:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (99 votes), past polls