这两个术语是什么?


当前回答

Greedy quantifier Lazy quantifier Description
* *? Star Quantifier: 0 or more
+ +? Plus Quantifier: 1 or more
? ?? Optional Quantifier: 0 or 1
{n} {n}? Quantifier: exactly n
{n,} {n,}? Quantifier: n or more
{n,m} {n,m}? Quantifier: between n and m

加一个?给量词,使其不贪婪,即懒惰。

例子: 测试字符串:stackoverflow 贪心reg表达式:s.*o输出:stackoverflow Lazy reg表达式:s.*?O输出:stackoverflow

其他回答

贪婪意味着你的表达式将匹配尽可能大的组,懒惰意味着它将匹配尽可能小的组。对于这个字符串:

abcdefghijklmc

这个表达式是:

a.*c

贪婪匹配将匹配整个字符串,而懒惰匹配将只匹配第一个abc。

试着理解以下行为:

    var input = "0014.2";

Regex r1 = new Regex("\\d+.{0,1}\\d+");
Regex r2 = new Regex("\\d*.{0,1}\\d*");

Console.WriteLine(r1.Match(input).Value); // "0014.2"
Console.WriteLine(r2.Match(input).Value); // "0014.2"

input = " 0014.2";

Console.WriteLine(r1.Match(input).Value); // "0014.2"
Console.WriteLine(r2.Match(input).Value); // " 0014"

input = "  0014.2";

Console.WriteLine(r1.Match(input).Value); // "0014.2"
Console.WriteLine(r2.Match(input).Value); // ""

贪婪量词就像美国国税局

他们会尽量多拿。例如,匹配这个正则表达式:.*

The $50000

再见了,银行余额。

这里有一个例子:贪婪的例子

非贪婪量词——他们拿走的越少越好

要求退税:国税局突然变得不贪心了,退税越少越好:也就是说,他们用了这个量词:

(.{2,5}?)([0-9]*)与此输入:$50,000

第一组是不需要的,只匹配5美元-所以我从5万美元的输入中得到5美元的退款。

看这里:非贪婪的例子。

为什么我们需要贪婪和非贪婪?

如果你试图匹配一个表达式的某些部分,这就变得很重要。有时候你不想把所有的东西都搭配起来——越少越好。有时候你想要尽可能的匹配。仅此而已。

你可以使用上面链接中的例子。

(用来帮助你记忆的比喻)。

为了进一步说明懒惰,这里有一个例子,乍一看可能不太直观,但从Suganthan Madhavan Pillai的回答中解释了“逐渐扩大比赛”的想法。

input -> some.email@domain.com@
regex -> ^.*?@$

这个输入的Regex将有一个匹配。乍一看,有人可能会说LAZY match(".*?@")将在第一个@停止,之后它将检查输入字符串结束("$")。按照这个逻辑,有人会得出没有匹配的结论,因为输入字符串在第一个@之后没有结束。

但正如你所看到的,情况并非如此,即使我们使用非贪婪(懒惰模式)搜索,regex也会继续前进,直到它命中秒@并有一个MINIMAL匹配。

据我所知,大多数正则表达式引擎默认是贪婪的。在量词末尾添加问号将启用惰性匹配。

正如@Andre S在评论中提到的。

贪婪:继续搜索,直到条件不满足。 Lazy:当条件满足时停止搜索。

参考下面的例子,了解什么是贪婪的,什么是懒惰的。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String args[]){
        String money = "100000000999";
        String greedyRegex = "100(0*)";
        Pattern pattern = Pattern.compile(greedyRegex);
        Matcher matcher = pattern.matcher(money);
        while(matcher.find()){
            System.out.println("I'm greedy and I want " + matcher.group() + " dollars. This is the most I can get.");
        }
        
        String lazyRegex = "100(0*?)";
        pattern = Pattern.compile(lazyRegex);
        matcher = pattern.matcher(money);
        while(matcher.find()){
            System.out.println("I'm too lazy to get so much money, only " + matcher.group() + " dollars is enough for me");
        }
    }
}

The result is:
I'm greedy and I want 100000000 dollars. This is the most I can get.

I'm too lazy to get so much money, only 100 dollars is enough for me