使用/.*?/的利润是多少? [英] What's the profit of using /.*?/

查看:130
本文介绍了使用/.*?/的利润是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一些Rails代码中(黄瓜特征的步骤定义,javascripts, rails_admin gem)我发现这个正则表达式部分:

In some Rails code (cucumber features' steps definitions, javascripts, rails_admin gem) I found this regular expression parts:

string =~ /some regexp.+rules should match "(.*?)"/i

我在正则表达式上有一些知识,我知道 * 符号类似,但是星号表示零和更多,问号表示可能存在或可能不是

I do have some knowledge at regular expressions and i know that * and ? symbols are similar but whilst asterisk means zero and more, the question mark means could be present or could be not.

因此,使用符号组旁边的问号会在要测试的词组中出现不需要的

So, using the question mark near the group of symbols makes its presence non-required within the phrase being tested. What's the... well... the trick of using it near the non-required already group (skipping requirement is made using the asterisk afaik)?

推荐答案

紧跟在量词之后(例如 * ),它不y。所以尽管默认是 * 尽可能多地消耗, *?尽可能少匹配。

Right after a quantifier (like *), the ? has a different meaning and makes it "ungreedy". So while the default is that * consumes as much as possible, *? matches as little as possible.

在特定情况下,这与以下字符串相关:

In your specific case, this is relevant for strings like this:

some regexp rules should match "some string" or "another"

没有问号,正则表达式匹配完整字符串(因为。* 可以像任何其他东西一样消费)和 另一个被捕获。使用问号,匹配将尽快停止(因此在 ...一些字符串),并且只捕获一些字符串

Without the question mark the regex matches the full string (because .* can consume " just like anything else) and some string" or "another is captured. With the use of the question mark, the match will stop as soon as possible, (so after ...some string") and will capture only some string.

进一步阅读。

这篇关于使用/.*?/的利润是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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