skip to Main Content

ANSWERED

Javascript Regex.

Given these..

string: ddd the ! key

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).

2

Answers


  1. (?!the) matches at "he". You could update the regular expression to ensure there’s a space before the word or it is the start of the string.

    / !(?<=( |^)(?!the)w+ !)/
    
    Login or Signup to reply.
  2. 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(?!theb)w+ !)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search