Search code examples
javascriptregexregex-lookarounds

Problem with javascript-regex matching, negative look-ahead inside a lookbehind


Given this string: ddd the ! key

and the Javascript regex: / !(?<=(?!the)\w+ !)/

I want to know the reason why the regex does NOT fail.

I expect the regex to fail matching, it doesn't, I don't know why. i found an alternative that works, which is..

/ !(?<=\w+(?<!the) !)/

but i still prefer to make the one above work, because it's faster(maybe).


Solution

  • If you don't want the assertion to be true at a partial word match, you could also start with a word boundary.

    So after matching a space and exclamation mark, assert that what is left to the current position is a word boundary not directly followed by a word starting with the

     !(?<=\b(?!the)\w+ !)
    

    See a regex demo

    If it should be the whole word the then you can add a word boundary after it

     !(?<=\b(?!the\b)\w+ !)