Don't forget to watch out for phrases like "Get the theist!" or "He would've vented had he had the time." Some of the above regexes would improperly remove the seemingly duplicated words ("the" and "ve") from the middles of those phrases.

You can avoid this problem with a positive lookahead (props to japhy for the compiled word and nonword regexes):

$word = qr/ \w [\w'-]* /x; $nonword = qr/ [^\w'-]+ /x; $text =~ s/ \b ($word) $nonword (?= \1 $nonword ) //xg;

This looks ahead to make sure that second and seemingly duplicated word is actually a separate word, and not part of another one. You can't simply use a \b at the end, since that would still mishandle phrases like "The can can't cant?"

On the other hand, I have no idea whether this is faster or more efficient. Plus, you'll still have to watch out for intentionally duplicated words, as in "He didn't know that that regex was going to do so much damage."

-jehuni


In reply to Re: most efficient regex to delete duplicate words by jehuni
in thread most efficient regex to delete duplicate words by Anonymous Monk

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.