问题描述
Pattern ptn = Pattern.compile(a *);
Matcher mtch = ptn.matcher(bbaac);
if(mtch.find()){
System.out.println(mtch.group());
}
输出 - 不打印
Pattern ptn = Pattern.compile(a +);
Matcher mtch = ptn.matcher(bbaac);
if(mtch.find()){
System.out.println(mtch.group());
}
输出 - aa
* 和
+
的行为感到困惑(两者都是是贪婪的量词)。 请让我知道为什么在第一种情况下输出没有打印,即
a *
贪婪它应该返回 aa
作为匹配。你的代码中唯一错误的是你没有遍历匹配的所有找到的子序列。
while(mtch.find()){//< - 不在这里
System.out。的println(mtch.group());
}
模式a *
将匹配两个空字符串,然后在字符串中匹配aa
,因为它是预期的,因为 *
量词允许零次出现。但是, +
量词与空字符串不匹配,因为它匹配一个或多个出现()。
bbaac
^ ^ ^ ^ ^< - 匹配*
的案例
Pattern ptn = Pattern.compile("a*");
Matcher mtch = ptn.matcher("bbaac");
if(mtch.find()){
System.out.println(mtch.group());
}
Output - prints nothing
Pattern ptn = Pattern.compile("a+");
Matcher mtch = ptn.matcher("bbaac");
if(mtch.find()){
System.out.println(mtch.group());
}
Output - aa
I know that it's a very simple problem but still I got confused seeing the behaviour of *
and +
(both are greedy quantifier).Please let me know why in first case output prints nothing i.e a*
is greedy it should return aa
as match.
The only thing wrong in your code is that you are not looping over all the found subsequence of the Matcher.
while (mtch.find()) { // <-- not if here
System.out.println(mtch.group());
}
The pattern "a*"
will match two empty Strings before matching "aa"
in your String, as it is expected because the *
quantifier allows for zero occurrences. However, the +
quantifier will not match the empty Strings since it matches one or more occurences (tutorial about quantifiers).
b b a a c
^ ^ ^ ^ ^ <-- matches for case of *
这篇关于请解释*贪婪量词的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!