这两个术语是什么?


当前回答

来自正则表达式

regular中的标准量词 表达式是贪婪的,这意味着它们 尽可能多地匹配,只给予 回视需要进行匹配 正则表达式的剩余部分。 通过使用惰性量词,的 表达式尝试最小匹配 第一。

其他回答

来自正则表达式

regular中的标准量词 表达式是贪婪的,这意味着它们 尽可能多地匹配,只给予 回视需要进行匹配 正则表达式的剩余部分。 通过使用惰性量词,的 表达式尝试最小匹配 第一。

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

abcdefghijklmc

这个表达式是:

a.*c

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

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

贪婪意味着它将消耗你的模式,直到没有剩下的,它不能再看了。

Lazy会在遇到您请求的第一个模式时立即停止。

我经常遇到的一个常见的例子是\s*-\s*?([0-9]{2}\s*-\s*?[0-9]{7})

第一个\s*被归类为贪婪的,因为有*,它会在遇到数字后寻找尽可能多的空白,然后寻找破折号“-”。第二个s*在哪里?懒惰是因为*的存在吗?这意味着它将查看第一个空白字符并在那里停止。

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

正如@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