这两个术语是什么?


当前回答

试着理解以下行为:

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

其他回答

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

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

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

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

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

来自正则表达式

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

摘自www.regular-expressions.info

贪心:贪心量词首先尝试重复标记尽可能多的次数 尽可能,并逐渐放弃匹配,因为引擎返回寻找 一场全面的比赛。

惰性:惰性量词首先根据需要重复标记的次数,然后 随着引擎通过正则表达式返回到,逐渐扩展匹配 找到一个整体匹配。

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

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

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