php正则表达式:后视和前瞻和贪婪问题 [英] php regex: lookbehind and lookahead and greediness problem
本文介绍了php正则表达式:后视和前瞻和贪婪问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这应该很简单,但我是个菜鸟,我一生都无法弄清楚.我正在尝试使用正则表达式来匹配特殊打开/关闭标签内的文本:[p2][/p2]
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]
所以在本文中:
apple [p2]banana[/p2] grape [p2]lemon[/p2]
它应该匹配banana"和lemon".到目前为止我处理的正则表达式是:
it should match "banana" and "lemon". The regex I've worked up so far is:
(?<=\[p2\]).+(?=\[\/p2\])
但这太贪心了.它匹配以香蕉中的b"开头并以柠檬中的n"结尾,匹配banana[/p2] 葡萄 [p2]lemon.香蕉和柠檬如何搭配?
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?
推荐答案
应该这样做:
(?<=\[p2\]).+?(?=\[\/p2\])
我添加了问号以使量词不贪婪.
I added the question mark to make the quantifier non-greedy.
这篇关于php正则表达式:后视和前瞻和贪婪问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文