Regular Expression for UpperCase Letters In A String

前端 未结 8 1601
野性不改
野性不改 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:52

    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++;
        }
    }
    

提交回复
热议问题