Please explain the working of * greedy quantifier

后端 未结 2 1618
孤街浪徒
孤街浪徒 2021-01-22 02:13
Pattern ptn  = Pattern.compile(\"a*\");
Matcher mtch  = ptn.matcher(\"bbaac\");
if(mtch.find()){
    System.out.println(mtch.group());
}

Output - print

2条回答
  •  终归单人心
    2021-01-22 02:44

    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 *
    

提交回复
热议问题