Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Match only the last instance of a regex that I only know partially

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 /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 Demo 1

RegEx Details:

  • foo: Match foo
  • (?:(?!foo|bar).)+: Match 1+ of any character as long as it is not immediately followed by a foo or bar.
  • bar: Match bar
  • (?!.*foo.+bar): Make sure we don’t have any foo..bar match 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)

RegEx Demo 2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading