Search code examples
regexregex-lookaroundsregex-negation

Negating duplicate words pattern


I am new to regex and have the following pattern that detects duplicate words separated with dashes

\b(\w+)-+\1\b
// matches: hey-hey
// not matches: hey-hei

What I really need is a negated version of this pattern. I've tried negative lookahead, but no good.

(?!\b(\w+)-+\1\b)

Solution

  • You can use

    \b(\w+)-+(?!\1\b)\w+
    

    See the regex demo. Details:

    • \b - a word boundary
    • (\w+) - Group 1: one or more word chars
    • -+ - one or more hyphens
    • (?!\1\b)\w+ - one or more word chars that are not equal to the first capturing group value.