Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
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 scrutinizing the Monastery: (16)
As of 2015-07-31 16:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (279 votes), past polls