请解释*贪婪量词的工作原理 [英] Please explain the working of * greedy quantifier

查看:131
本文介绍了请解释*贪婪量词的工作原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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 *

这篇关于请解释*贪婪量词的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆