这两个术语是什么?
当前回答
贪婪的人会尽可能多地消费。在http://www.regular-expressions.info/repeat.html中,我们看到了试图将HTML标记与<.+>匹配的示例。假设你有以下情况:
<em>Hello World</em>
你可能认为…+ >(。表示任何非换行符,+表示一个或多个)将只匹配<em>和</em>,而实际上它将非常贪婪,并从第一个<到最后一个>。这意味着它将匹配<em>Hello World</em>,而不是你想要的。
将其设置为惰性(<.+?>)将防止这种情况。通过添加?在+之后,我们告诉它重复尽可能少的次数,所以它遇到的第一个>就是我们想要停止匹配的地方。
我鼓励你下载RegExr,这是一个很好的工具,可以帮助你探索正则表达式——我一直在用它。
其他回答
来自正则表达式
regular中的标准量词 表达式是贪婪的,这意味着它们 尽可能多地匹配,只给予 回视需要进行匹配 正则表达式的剩余部分。 通过使用惰性量词,的 表达式尝试最小匹配 第一。
'Greedy'表示匹配最长的字符串。
'Lazy'表示匹配最短的字符串。
例如,贪婪的h.+l匹配'hello'中的'hell',但懒惰的h.+?L和“hel”匹配。
据我所知,大多数正则表达式引擎默认是贪婪的。在量词末尾添加问号将启用惰性匹配。
正如@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
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); // ""
推荐文章
- (grep)正则表达式匹配非ascii字符?
- 如何在保持原始字符串的同时对字符串执行Perl替换?
- 创建正则表达式匹配数组
- *的区别是什么?和。*正则表达式?
- 如何将“camelCase”转换为“Camel Case”?
- 在Java中使用正则表达式提取值
- Java中的正则表达式命名组
- 使用正则表达式搜索和替换Visual Studio代码
- 使用split("|")按管道符号拆分Java字符串
- 替换字符串中第一次出现的模式
- “\d”在正则表达式中是数字吗?
- 如何检查一行是否为空白使用正则表达式
- RegEx以确保字符串至少包含一个小写字符、大写字符、数字和符号
- Java Regex捕获组
- 用JavaScript检测文本中的url