Ultra-non-greedy Regex?

  • A+
Category:Languages

This regex...

abc.*?xyz 

...is non-greedy. If you test it on this string...

abc 123 xyz xyz 

...it matches abc 123 xyz. The second xyz is not matched because of its non-greediness. But if you test it on this string...

abc abc 123 xyz 

...it matches the whole string. Seems like .*? is only non-greedy to the RIGHT of its position but not to the LEFT.

How do I make a regex like foo.*?bar that's non-greedy in both directions?


Random test case example:

abc abc 123 xyz xyz 456 abc abc xyz 000 xyz 

Desired result:

Match 1: abc 123 xyz
Match 2: abc xyz

 


You can just make sure that the first part isn't in the inner part:

abc((?!abc).)*?xyz 

If you want to avoid repeating the first part:

(abc)((?!/1).)*?xyz 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: