Today, I found myself looking for a regular expression that matches only the last occurrence of a given expression. As I’m still not a regex mastermind I couldn’t come up with it just like that.
The key to the solution is a so called “negative lookahead“. A lookahead doesn’t consume characters in the string, but only asserts whether a match is possible or not. So if you wanted to extract the last “foo” in the text “foo bar foo bar foo” your regex would look like this:
If you used the DOTALL option the above expression would even work correctly on a multi-line text such as
Of course the example is not taken from a real life scenario as it doesn’t matter which “foo” is matched as they’re all the same anyway. The expression would with no doubt be more complicated, but I hope you get the point.