php 正则表达式:lookbehind、lookahead 和贪婪问题

发布于 2024-08-10 18:41:40 字数 355 浏览 2 评论 0原文

这应该很简单,但我是个菜鸟,我一生都无法弄清楚。我正在尝试使用正则表达式来匹配特殊打开/关闭标记内的文本: [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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吃不饱 2024-08-17 18:41:40

应该这样做:

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

我添加了问号以使量词变得非贪婪。

This should do it:

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

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

缺⑴份安定 2024-08-17 18:41:40

您可以使用标准 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文