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 *
The issue is that there are 5 matches, and you only check for the first one which is an empty string as a*
can match an empty string (to be more exact, it matches the empty space before the character it cannot match and at the end of string).
Use while
instead of if
.
See IDEONE demo:
String s = "bbaac";
Pattern pattern = Pattern.compile("a*");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
System.out.println(matcher.group(0));
}
The number of matches is 5:
b
b
aa
c
andc
.Using a+
, with the +
quantifier meaning 1 or more occurrences, no empty matches will get extracted and you will only get aa
.
See the empty strings on regex101.com: