这两个术语是什么?
当前回答
贪婪匹配。正则表达式的默认行为是贪婪的。这意味着它会尝试提取尽可能多的数据,直到它符合某个模式,即使在语法上只需要较小的部分就足够了。
例子:
import re
text = "<body>Regex Greedy Matching Example </body>"
re.findall('<.*>', text)
#> ['<body>Regex Greedy Matching Example </body>']
它提取了整个字符串,而不是直到' > '第一次出现才匹配。这是regex默认的贪婪或“全部拿走”行为。
另一方面,懒惰匹配“需要的越少越好”。这可以通过添加一个?在图案的最后。
例子:
re.findall('<.*?>', text)
#> ['<body>', '</body>']
如果只希望检索第一个匹配项,则使用search方法。
re.search('<.*?>', text).group()
#> '<body>'
来源:Python Regex Examples
其他回答
摘自www.regular-expressions.info
贪心:贪心量词首先尝试重复标记尽可能多的次数 尽可能,并逐渐放弃匹配,因为引擎返回寻找 一场全面的比赛。
惰性:惰性量词首先根据需要重复标记的次数,然后 随着引擎通过正则表达式返回到,逐渐扩展匹配 找到一个整体匹配。
试着理解以下行为:
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); // ""
'Greedy'表示匹配最长的字符串。
'Lazy'表示匹配最短的字符串。
例如,贪婪的h.+l匹配'hello'中的'hell',但懒惰的h.+?L和“hel”匹配。
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。