使用/.* 有什么好处?/ [英] What's the profit of using /.*?/

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

问题描述

在一些 Rails 代码(黄瓜功能的步骤定义、javascript、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.

因此,在符号组附近使用问号会使它在被测试的短语中不需要.什么是......嗯......在不需要的已经组附近使用它的技巧(使用星号 afaik 进行跳过要求)?

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)?

推荐答案

紧跟在量词之后(如*),?有不同的含义,使之成为不贪".因此,虽然默认是 * 尽可能多地消耗,但 *? 尽可能少地匹配.

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"

没有问号,正则表达式匹配完整的字符串(因为 .* 可以像其他任何东西一样使用 "some string" 或 "another 被捕获.使用问号,匹配将尽快停止,(所以在 ...some string" 之后)并且将仅捕获 some string.

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天全站免登陆