Wednesday, October 31, 2018

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.


Answer



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



.*(?


(? 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.



.*(?


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


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...