Regex匹配两个字符串之间的最后一次出现

时间:2021-01-21 21:46:39

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.

问题是,字符串中有重复的“abc”,所以它返回“abcdeabc…”但是我只想匹配最后一个abc和xyz之间的任何东西。这是可能的吗?如果是的话,我怎么做呢?谢谢你!

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

试一试:https://regex101.com/r/gS9Xso/3

2 个解决方案

#1


2  

Try this pattern:

试试这个模式:

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

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

前导。*将消耗所有内容直到最后一个abc,然后该数字将被捕获。

Demo

We can also try using the following pattern:

我们也可以尝试使用以下模式:

.*abc(.*?)xyz

Here is a demo for the second pattern:

下面是第二个模式的演示:

Demo

#2


0  

This should work well.

这应该工作得很好。

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

See it on Debuggex

看到它在Debuggex

#1


2  

Try this pattern:

试试这个模式:

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

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

前导。*将消耗所有内容直到最后一个abc,然后该数字将被捕获。

Demo

We can also try using the following pattern:

我们也可以尝试使用以下模式:

.*abc(.*?)xyz

Here is a demo for the second pattern:

下面是第二个模式的演示:

Demo

#2


0  

This should work well.

这应该工作得很好。

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

See it on Debuggex

看到它在Debuggex