Starting from the end of a string, how do I stop capturing once I reach the first occurrence of a character group?

时间:2018-07-25 05:04:16

标签: php regex

I'm trying to capture all characters starting from the end of a string, but only until I find abc. My current regex is:

/(?<=abc)(.+?)$/

This seems to work, but if I have two or more occurrences of abc it will capture all but the last one. Take this string as an example:

foo bar abc abc foo bar will capture foo bar abc( abc foo bar).

Why does this happen, and how can I get the capture to stop at the first occurrence of abc? So:

foo bar abc abc( foo bar) regex101

1 个答案:

答案 0 :(得分:1)

You can use

(?<=abc)((?!abc).)+?$

to require that every repeated character is not the "a" in an "abc". (repeating this until the end of the string ensures that there is no "abc" contained in the match)

https://regex101.com/r/BoK0Mh/3

Why does this happen

Because regular expressions start at the beginning of the string and work rightwards until they find a match - even when it starts with lookbehind, they don't start at the end and work leftwards.