For the life of me, I can\'t figure out why this regular expression is not working. It should find upper case letters in the given string and give me the count. Any ideas are we
It should find upper case letters in the given string and give me the count.
No, it shouldn't: the ^
and $
anchors prevent it from doing so, forcing to look for a non-empty string composed entirely of uppercase characters.
Moreover, you cannot expect a group count in an expression that does not define groups to be anything other than zero (no matches) or one (a single match).
If you insist on using a regex, use a simple [A-Z]
expression with no anchors, and call matcher.find()
in a loop. A better approach, however, would be calling Character.isUpperCase on the characters of your string, and counting the hits:
int count = 0;
for (char c : str.toCharArray()) {
if (Character.isUpperCase(c)) {
count++;
}
}