Regex for string not ending with given suffix

I have not been able to find a proper regex to match any string not ending with some condition. For example, I don't want to match anything ending with an a.

This matches

b
ab
1

This doesn't match

a
ba

I know the regex should be ending with $ to mark the end, though I don't know what should preceed it.

Edit: The original question doesn't seem to be a legit example for my case. So: how to handle more than one character? Say anything not ending with ab?

I've been able to fix this, using this thread:

.*(?:(?!ab).).$

Though the downside with this is, it doesn't match a string of one character.


You don't give us the language, but if your regex flavour support look behind assertion, this is what you need:

.*(?<!a)$

(?<!a) is a negated lookbehind assertion that ensures, that before the end of the string (or row with m modifier), there is not the character "a".

See it here on Regexr

You can also easily extend this with other characters, since this checking for the string and isn't a character class.

.*(?<!ab)$

This would match anything that does not end with "ab", see it on Regexr


Use the not (^) symbol:

.*[^a]$

If you put the ^ symbol at the beginning of brackets, it means "everything except the things in the brackets." $ is simply an anchor to the end.

For multiple characters, just put them all in their own character set:

.*[^a][^b]$