php 正则表达式:lookbehind、lookahead 和贪婪问题
这应该很简单,但我是个菜鸟,我一生都无法弄清楚。我正在尝试使用正则表达式来匹配特殊打开/关闭标记内的文本: [p2][/p2]
因此在本文中:
apple [p2]banana[/p2] grape [p2]lemon[/p2]
它应该匹配“香蕉”和“柠檬”。到目前为止我已经研究过的正则表达式是:
(?<=\[p2\]).+(?=\[\/p2\])
但这太贪婪了。它匹配以banana 中的“b”开始,以lemon 中的“n”结束,匹配banana[/p2]葡萄[p2]lemon。香蕉和柠檬如何搭配?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
应该这样做:
我添加了问号以使量词变得非贪婪。
This should do it:
I added the question mark to make the quantifier non-greedy.
您可以使用标准 perl 样式匹配修饰符并添加 ? 来代替使用正则表达式修饰符。在+或*之后告诉特定部分是非贪婪的。上面提到了,但是特异性会有所帮助。
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.