Regular Expression for UpperCase Letters In A String

前端 未结 8 1603
野性不改
野性不改 2021-02-20 03:15

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

8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-20 03:47

    It doesn't work because you have 2 problems:

    1. Regex is incorrect, it should be "[A-Z]" for ASCII letter or \p{Lu} for Unicode uppercase letters
    2. You're not calling while (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;
    

提交回复
热议问题