Pattern ptn = Pattern.compile(\"a*\");
Matcher mtch = ptn.matcher(\"bbaac\");
if(mtch.find()){
System.out.println(mtch.group());
}
Output - print
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 *