Regular Expression for UpperCase Letters In A String

Viewed 46230

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 welcome.

Here is the unit test code:

public class RegEx {

    @Test
    public void testCountTheNumberOfUpperCaseCharacters() {
        String testStr = "abcdefghijkTYYtyyQ";
        String regEx = "^[A-Z]+$";

        Pattern pattern = Pattern.compile(regEx);

        Matcher matcher = pattern.matcher(testStr);

        System.out.printf("Found %d, of capital letters in %s%n", matcher.groupCount(), testStr);

    }
}
9 Answers

Change the regular expression to [A-Z] which checks all occurrences of capital letters

Please refer the below example which counts number of capital letters in a string using pattern

@Test
public void testCountTheNumberOfUpperCaseCharacters() {
    Pattern ptrn = Pattern.compile("[A-Z]");
    Matcher matcher = ptrn.matcher("ivekKVVV");
    int from = 0;
    int count = 0;
    while(matcher.find(from)) {
        count++;
        from = matcher.start() + 1;
    }
    System.out.println(count);
}

}

You can also use Java Regex, for example:

.+[\p{javaUpperCase}].+ 

An example from my work project: RegEx Result Image

Here's a solution for Java 9 and later that makes use of the results() method of Matcher, which returns a stream of the results, out of which the entries can be counted. The suggestion from @Sergey Kalinichenko to remove the ^ and $ anchors has also been incorporated into the regex string.

public class RegEx {
 @Test
 public void testCountTheNumberOfUpperCaseCharacters() {
    String testStr = "abcdefghijkTYYtyyQ";
    String regEx = "\\p{Lu}";

    Pattern pattern = Pattern.compile(regEx);
    Matcher matcher = pattern.matcher(testStr);
    long count = matcher.results().count();
    
    System.out.printf("Found %d of capital letters in %s%n", count, testStr);

 }
}
Related