Regular expressions aren't particularly good at counting simple things. Think ant+sledgehammer. They are good at busting complex strings up into pieces.
Anyway, here's one solution the OP is interested in - using a regex to count 'a's:
public class Reggie {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("[^a]*a");
Matcher matcher = pattern.matcher("aaabbbaaabbabababaaabbbbba");
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println(count+" matches");
}
}
This is a pretty slow way to do it, as pointed out by others. Worse, it isn't the easiest and certainly isn't the most likely to be bug-free. Be that as it may, if you wanted something a little more complex than 'a' then the regex would become more appropriate as the requested string got more complex. For example, if you wanted to pick dollar amounts out of a long string then a regex could be the best answer.
Now, about the regex: [^a]*a
This [^a]*
means 'match zero or more non-'a' characters. This allows us to devour non-'a' crud from the beginning of a string: If the input is 'bbba' then [^a]*
will match 'bbb'. It doesn't match the 'a'. Not to worry, the trailing 'a' in the regex says, "match exactly one 'a'". So our regex says, "match zero or more non-'a' characters that are followed by an 'a'."
Ok. Now you can read about Pattern and Matcher. The nutshell is that the Pattern is a compiled regular expression. It is expensive to compile a regex so I make mine static so they only get compiled once. The Matcher is a class that will apply a string to a Pattern to see if it matches. Matcher has state information that lets it crawl down a string applying a Pattern repeatedly.
The loop basically says, "matcher, crawl down the string finding me the next occurrence of the pattern. If we find it, increment the counter." Note the character sequences being found by Matcher isn't just 'a'. It is finding sequences like the following: 'a', 'bbba', 'bba', 'ba', etc. That is, strings that don't contain an 'a' except for their last character.