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

Regex expression to get the string between two strings,or until either end of the main string

I am trying to write a regex that gets the content between two strings, String1 and String2 but in case either of the two strings are not present I want to match until the end of the main string.
For example: hi_foo123xyz2-3bar_hello, foo123xyz2-3bar , foo123xyz2-3 123xyz2-3bar and 123xyz2-3 the intended match is 123xyz2-3.

I tried different approaches using Lookaheads and Lookbehinds and I feel that I only need a single step but It seems far from reach.
The closest I could get is something like this

(?<=foo).*?(?=bar|$)

I also tried

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|$)

but it seems to break everything.

>Solution :

The trick is to match ^ only when there is no foo using this expression ^(?!.*foo), then create an alternation of that or a lookbehind for foo.

Similarly, use a lookahead for bar or end of input $.

(^(?!.*foo)|(?<=foo)).*?((?=bar)|$)

See live demo.

Recall that alternations are match left to right – ie the right is only attempted if the left doesn’t match.

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