I would suggest not splitting the string into an array (Update: at least not by words), since this kind of matching sounds like it'd be easier to do with two regexes - one for the stop words, and one for the phrases. Have a look at my node Building Regex Alternations Dynamically. Then, I'd suggest you process the input string piece by piece, because that should make your requirement of not replacing stop words inside the longer matches possible - see "Global Matching" in perlretut, and a more complex example of the usage of m/\G.../gc in perlop under "\G assertion".

Update: Here's a solution that takes a simpler route than m/\G.../gc, using split:

use warnings; use strict; my %stops = map {$_=>1} qw/ I am the of and /; my %terms = ( 'manager of sales' => 1 ); my $str = 'I am the senior manager of sales and of marketing'; my ($re_stops) = map {qr/\b(?:$_)\b/i} join '|', map {quotemeta} sort { length $b <=> length $a or $a cmp $b } keys %stops; my ($re_terms) = map {qr/\b(?:$_)\b/i} join '|', map {quotemeta} sort { length $b <=> length $a or $a cmp $b } keys %terms; my @s = split /($re_terms)/, $str; for my $i (0..$#s) { if ($i%2) { print "*", $s[$i], "*\n"; } else { $s[$i] =~ s/$re_stops//g; $s[$i] =~ s/^\s+|\s+$//g; print $s[$i], "\n"; } } __END__ senior *manager of sales* marketing

Update 2: Added the case-insenstive matching flag /i to the regexes and fixed a typo in the text.


In reply to Re: Match strings in order of character length, and remove the string from further processing (updated) by haukex
in thread Match strings in order of character length, and remove the string from further processing by ScarletRoxanne

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.