字符串中UpperCase字母的正则表达式

Dav*_*vid 10 java regex

对于我的生活,我无法弄清楚为什么这个正则表达式不起作用.它应该在给定的字符串中找到大写字母并给我计数.欢迎任何想法.

这是单元测试代码:

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);

    }
}
Run Code Online (Sandbox Code Playgroud)

anu*_*ava 17

它不起作用,因为你有2个问题:

  1. 正则表达式不正确,它应该是"[A-Z]"ASCII字母或\p{Lu}Unicode大写字母
  2. while (matcher.find())以前没打过电话matcher.groupCount()

正确的代码:

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);

}
Run Code Online (Sandbox Code Playgroud)

更新:使用这个更简单的单行代码来计算字符串中Unicode大写字母的数量:

int countuc = testStr.split("(?=\\p{Lu})").length - 1;
Run Code Online (Sandbox Code Playgroud)


Mar*_*nik 10

  1. 你没有打电话matchesfind在匹配上.它没有做任何工作.

  2. getGroupCount是一种错误的调用方法.你的正则表达式没有捕获组,即使它没有,它也不会给你字符数.

你应该使用find,但使用不同的正则表达式,没有锚点.我还建议使用正确的Unicode字符类:"\\p{Lu}+".在while (m.find())循环中使用它,并累计从m.group(0).length()每一步获得的字符总数.


M21*_*1B8 6

这应该做你想要的,

@Test
public void testCountTheNumberOfUpperCaseCharacters() {
  String testStr = "abcdefghijkTYYtyyQ";
  String regEx = "[A-Z]+";
  Pattern pattern = Pattern.compile(regEx);
  Matcher matcher = pattern.matcher(testStr);
  int count = 0;
  while (matcher.find()) {
    count+=matcher.group(0).length();
  }
  System.out.printf("Found %d, of capital letters in %s%n", count, testStr);
}
Run Code Online (Sandbox Code Playgroud)