Louis Tran
Louis Tran

Reputation: 1156

Regex match last occurrence between 2 strings

I have a string like this:

abcabcdeabc...STRING INSIDE...xyz

I want to find "...STRING INSIDE..." so I'm using the regex below to match it:

(?<=abc).*(?=xyz)

The issue is there are duplicated "abc" in the string so it returns "abcdeabc...STRING INSIDE..." but I only want to match anything between the last "abc" and "xyz". Is this possible? And if yes, how can I achieve this? Thank you.

Try it here: https://regex101.com/r/gS9Xso/3

Upvotes: 2

Views: 1662

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

Try this pattern:

.*(?<=abc)(.*)(?=xyz)

The leading .* will consume everything up until the last abc, then the number will be captured.

Demo

We can also try using the following pattern:

.*abc(.*?)xyz

Here is a demo for the second pattern:

Demo

Upvotes: 2

OverCoder
OverCoder

Reputation: 1603

This should work well.

[^\d]*abc(\d+)xyz[^\d]*

See it on Debuggex

Upvotes: 0

Related Questions