非贪婪匹配仍然过于贪婪 [英] Non-greedy match is still too greedy

查看:59
本文介绍了非贪婪匹配仍然过于贪婪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要捕获最短匹配项的正则表达式模式,但在嵌套该模式的情况下,惰性匹配不起作用.这就是我的意思:

I have a regex pattern that needs to capture the shortest matches, but the lazy match isn't working in cases where that pattern is nested. Here's what I mean:

正则表达式:

/{{.*?}}/

示例字符串:

{{This}} is {{an example {{sentence}}}}

在上面的例子中,我希望拉取 {{This}}{{sentence}},因为它们是最短的匹配,但是我正在获取 {{This}}{{an example {{sentence}}.为什么非贪婪匹配仍然如此贪婪 - 或者更确切地说,我哪里出错了?

In the above example, I'm expecting to pull {{This}} and {{sentence}}, as these are the shortest matches, but instead I am getting {{This}} and {{an example {{sentence}}. Why is the non-greedy match still being so greedy - or rather, where am I going wrong?

推荐答案

尝试:{{[^{]*?}}这是利用{"字符不应出现在内部字符串中的事实.它确实符合您的预期.

Try: {{[^{]*?}} This is using the fact that the '{' character should not appear in the inner strings. It does match what you expect.

这篇关于非贪婪匹配仍然过于贪婪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆