对正则表达式感到困惑

发布于 2024-08-03 22:10:29 字数 221 浏览 1 评论 0原文

我想要匹配表达式 ${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 技术交流群。

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

发布评论

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

评论(3

看轻我的陪伴 2024-08-10 22:10:29

以及 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.

演出会有结束 2024-08-10 22:10:29

我首先删除表达式开头和结尾处的 .* - 这可能是匹配所有内容的。如果你尝试这样做,它有效吗?

\$\{.+\}

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?

\$\{.+\}
风吹雨成花 2024-08-10 22:10:29

“+”量词是贪婪的,因此它会尽可能多地匹配,而+? 则只匹配足够多的内容。

例如,对于“${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

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