对于我的生活,我无法弄清楚为什么这个正则表达式不起作用。它应该在给定的字符串中找到大写字母并给我计数。欢迎任何想法。
这是单元测试代码:
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 许可协议
您没有在匹配器上调用
matches
或find
。它没有做任何工作。getGroupCount
是错误的调用方法。您的正则表达式没有捕获组,即使有,也不会为您提供字符数。您应该使用
find
,但使用不同的正则表达式,一个没有锚点。我还建议使用正确的 Unicode 字符类:"\\p{Lu}+"
。在while (m.find())
循环中使用它,并在每一步中累积从m.group(0).length()
获得的字符总数。