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