I want to match just the last instance of a regular expression. For example in this string:
some text here foo word bar and foo word foo word foo word bar more text here
I am trying to only match the bolded portion. Here is what I have tried currently:
/foo?.+?bar/gi
However, it is keeping all of the italicized portion. What am I doing wrong?
>Solution :
You may use this regex that matches closes foo...bar pair without allowing any foo or bar in the middle:
foo(?:(?!foo|bar).)+bar(?!.*foo.+bar)
RegEx Details:
foo: Matchfoo(?:(?!foo|bar).)+: Match 1+ of any character as long as it is not immediately followed by afooorbar.bar: Matchbar(?!.*foo.+bar): Make sure we don’t have anyfoo..barmatch on RHS
If you are fine with getting your match in a capture group then consider this more efficient version of regex:
.*(foo(?:(?!foo|bar).)+bar)