Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: Count multiple pattern matches

by tilly (Archbishop)
on Dec 07, 2004 at 02:50 UTC ( #412815=note: print w/replies, xml ) Need Help??

in reply to Count multiple pattern matches

Use a capturing subgroup.
use strict; my @keywords=qw/foo bar 12345 abcd/; my $string = "foobarfoo1234523423412345abcdefsadfabc"; my %result; my $pattern = join "|", @keywords; while ($string =~ /($pattern)/ig) { $result{$1}++; } foreach my $s (keys %result){ print "$s=>$result{$s}\n"; }
As an efficiency note I'm not sure whether the pattern above keeps on getting recompiled. You may wish to benchmark a few variations. It is also possible that it is faster to match many times than it is to do one big complex match - I've certainly seen that happen in the past. And you should definitely look at Regexp::PreSuf.

As a bug note, if your strings are "foo", "bar", and "foobar", the original approach will correctly spot one of each in "foobar". This approach will not. (Depending on order it might spot "foobar" or it might spot "foo" and "bar".) This gets even more complicated if you're looking at things like "bazfoo" and "foobar".

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2020-08-08 18:02 GMT
Find Nodes?
    Voting Booth?
    Which rocket would you take to Mars?

    Results (52 votes). Check out past polls.