I am not trying to accomplish anything except understand why this specific regex does not work as intended:
/bty(?!t)b/i
Intended match:
- any string starting with ‘ty’ and not ending with ‘t’
From what I understood about negative lookbehind, it should match something not followed by something, and here i want to match tyX (X can be any character) as long as X is not ‘t’.
Should match:
tya
Should not match:
tyt
Using a negated set solves this easily, but I don’t understand why a negative lookahead doesn’t work.
2
Answers
(?!t)
is not a negative look behind, but a negative look ahead. You got that right further on in your question.(?!t)
asserts that there is not
at this position, without moving the current position.bty(?!t)b
cannot matchtyX
, as your regex requires ab
immediately afterty
. There is no provision for a third character in this pattern.b
asserts that the next character is not an alphanumerical, which already excludes "t", and so your regex is actually doing the same asbtyb
and so only the wordty
can be matched (case insensitive).To provide for longer words, you should add
w*
afterty
. To exclude words ending in a "t", you could use a negative look behind so to assert that the last character matched is not a "t":This will match all of the following:
It will not match:
Your problem can be solved without using of negative look behind.
The regex can be broken down as follows.