字符串中大写字母的正则表达式

新手上路,请多包涵

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

这是单元测试代码:

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

    }
}

原文由 David 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 574
2 个回答
  1. 您没有在匹配器上调用 matchesfind 。它没有做任何工作。

  2. getGroupCount 是错误的调用方法。您的正则表达式没有捕获组,即使有,也不会为您提供字符数。

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

原文由 Marko Topolnik 发布,翻译遵循 CC BY-SA 3.0 许可协议

它不起作用,因为您有两个问题:

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

}

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

 int countuc = testStr.split("(?=\\p{Lu})").length - 1;

原文由 anubhava 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题