Search code examples
regexregex-lookarounds

Match a word but not a larger word


I want a regex to match rov but there's a thousand occurences of prov that I'm not interested in, so I need to match rov but exclude prov.

I've tried /((?!prov).)*(rov)/i but that still matches the rov part in the word prov. I also tried /((?!prov).)*(^rov)/i but I can't use it, I need to match words like CreateRov, I can't use ^ or \b.

How can I do that?


Solution

  • You could use a negative lookahead to assert what is on the right is not prov right after matching a word boundary.

    Then match rov between matching 0+ word characters on the left and right.

    \b(?!\w*prov)\w*rov\w*\b
    
    • \b Word boundary
    • (?!\w*prov) Negative lookahead, assert what is on the right is not prov
    • \w*rov\w* Match rov between matching 0+ word chars on the left an right
    • \b Word boundary

    Regex demo