这两个术语是什么?


当前回答

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

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

试着理解以下行为:

    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); // ""

来自正则表达式

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

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

abcdefghijklmc

这个表达式是:

a.*c

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

'Greedy'表示匹配最长的字符串。

'Lazy'表示匹配最短的字符串。

例如,贪婪的h.+l匹配'hello'中的'hell',但懒惰的h.+?L和“hel”匹配。