对正则表达式感到困惑
我想要匹配表达式 ${foo} 和 ${bar}
"${" 开头并以 "}"
结尾的表达式>。
当然,正则表达式 .*\$\{.+\}.*
匹配整个表达式。
我的理解是,更改为不情愿的量词可以解决问题,但我发现 .*\$\{.+?\}.*
也匹配整个表达式。
我缺少什么?
I want to match expressions that begin with "${"
and end with "}"
in the expression ${foo} and ${bar}
.
The regex .*\$\{.+\}.*
matches the entire expression, of course.
My understanding was that changing to the reluctant quantifier would solve the problem, but I find that .*\$\{.+?\}.*
also matches the entire expression.
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以及 1800 INFORMATION 的建议一样,我会将点更改为其他内容:
如果出现两次,
+
将尽可能匹配}
字符串中的${}
。As well as the suggestion by 1800 INFORMATION i would change the dot to something else:
As the
+
will match as much as it can even a}
if you have two occurances of${}
in the string.我首先删除表达式开头和结尾处的
.*
- 这可能是匹配所有内容的。如果你尝试这样做,它有效吗?I would start by removing the
.*
at the start and the end of the expression - it is probably this that is matching everything. If you try this does it work?“+”量词是贪婪的,因此它会尽可能多地匹配,而+? 则只匹配足够多的内容。
例如,对于“${foo} some ${bar}”
“.+”-->匹配=“${foo}某事${bar}”
“.+?” -->匹配 =“${foo}”和“${bar}”。您必须迭代才能获得所有匹配项。
http://www.regular-expressions.info/repeat.html
The "+" quantifier is greedy, so it matches as much as it can, while +?, matches just enough.
For example, for "${foo} something ${bar}"
".+" --> match = "${foo} something ${bar}"
".+?" --> match = "${foo}" and "${bar}". You will have to iterate to get all the matches.
http://www.regular-expressions.info/repeat.html