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 browsing the Monastery: (7)
As of 2014-12-20 11:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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





    Results (95 votes), past polls