I have these strings (checking every line separately):
adminUpdate
adminDeleteEx
adminEditXe
adminExclude
listWebsite
listEx
Now I want to match anything that starts with admin
but does not ends with Ex
(case-insensitive)
So after applying regex I must match:
adminUpdate
adminEditXe
adminExclude
My current regex is /^admin[a-z]+(?!ex)$/gi
but it matches anything that starts with admin
Just a slight change:
/^admin[a-z]+(?<!ex)$/gi
^
Turn your look-ahead into a look-behind.
It is quite hard to explain in the current form. Basically, you need to reach the end of the string $
for the regex to match, and when it happens, (?!ex)
is at the end of the string, so it can't see anything ahead. However, since we are at the end of the string, we can use a look-behind (?<!ex)
to check whether the string ends with ex
or not.
Since look-around is zero-width, we can swap the position of (?<!ex)
and $
without changing the meaning (it does change how the engine searches for the matched string, though):
/^admin[a-z]+$(?<!ex)/gi
It is counter-intuitive to write it this way, but easier to see where my argument goes.
Another way to look at it is: due to the fact that (?!ex)
and $
are zero-width assertion, they are checked at the same position, and being at the end of the string $
implies you won't see anything ahead.