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 doesn't work because you have 2 problems:
"[A-Z]"
for ASCII letter or \p{Lu}
for Unicode uppercase letterswhile (matcher.find())
before matcher.groupCount()
Correct code:
public void testCountTheNumberOfUpperCaseCharacters() {
String testStr = "abcdefghijkTYYtyyQ";
String regEx = "(\\p{Lu})";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(testStr);
while (matcher.find())
System.out.printf("Found %d, of capital letters in %s%n",
matcher.groupCount(), testStr);
}
UPDATE: Use this much simpler one-liner code to count number of Unicode upper case letters in a string:
int countuc = testStr.split("(?=\\p{Lu})").length - 1;