Shortest match in regex from end

六月ゝ 毕业季﹏ 提交于 2019-12-01 21:39:36

Use negative lookahead assertion.

foo(?:(?!foo).)*?boo

DEMO

(?:(?!foo).)*? - Non-greedy match of any character but not of foo zero or more times. That is, before matching each character, it would check that the character is not the letter f followed by two o's. If yes, then only the corresponding character will be matched.

Why the regex foo.*?boo matches the complete string fooxxxxxxfooxxxboo?

Because the first foo in your regex matches both the foo strings and the following .*? will do a non-greedy match upto the string boo, so we got two matches fooxxxxxxfooxxxboo and fooxxxboo. Because the second match present within the first match, regex engine displays only the first.

.*(foo.*?boo)

Try this. Grab the capture i.e $1 or \1.

See demo.

https://regex101.com/r/nL5yL3/9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!