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

Answer: How do I match for several strings, matching the longest string first?

( #7778=categorized answer: print w/ replies, xml ) Need Help??

Q&A > regular expressions > How do I match for several strings, matching the longest stringfirst? contributed by chromatic

Another option is to arrange your search terms into a sorted list:
my @terms = sort { length $b <=> length $a } ('lymph', 'lymph node'); my @text = ('right lymph node', 'lymph fluid'); my %results; foreach my $term (@terms) { $results{$term} = (grep /\b$term\b/, @text); # find matches @text = grep !/\b$term\b/, @text; # remove matches } foreach (keys %results) { print "$_:\t", $results{$_}, "\n"; }
This is likely less expensive with more search terms than building a large regexp, but the grep unfound operation may not help.

Comment on Answer: How do I match for several strings, matching the longest string first?
Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (3)
As of 2014-09-24 04:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (245 votes), past polls