非贪婪匹配仍然过于贪婪 [英] Non-greedy match is still too greedy
问题描述
我有一个需要捕获最短匹配项的正则表达式模式,但在嵌套该模式的情况下,惰性匹配不起作用.这就是我的意思:
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屋!