php regex: lookbehind and lookahead and greediness problem

十年热恋 提交于 2019-12-01 03:04:24

问题


This should be simple but I'm a noob and I can't for the life of me figure it out. I'm trying to use regex to match text inside of special open/close tags: [p2][/p2]

So in this text:

apple [p2]banana[/p2] grape [p2]lemon[/p2]

it should match "banana" and "lemon". The regex I've worked up so far is:

(?<=\[p2\]).+(?=\[\/p2\])

But this is too greedy. It matches starting with the "b" in banana and ends with the "n" in lemon, matching banana[/p2] grape [p2]lemon. How do I just match banana and lemon?


回答1:


This should do it:

(?<=\[p2\]).+?(?=\[\/p2\])

I added the question mark to make the quantifier non-greedy.




回答2:


Instead of using a regex modifier, you can use the standard perl style match modifier and add a ? after + or * to tell that specific portion to be non-greedy. Mentioned above, but specificity can help.



来源:https://stackoverflow.com/questions/1731934/php-regex-lookbehind-and-lookahead-and-greediness-problem

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