对于我的一生,我无法弄清楚为什么这个正则表达式不起作用。它应该在给定的字符串中找到大写字母,并给我计数。任何想法都欢迎。
这是单元测试代码:
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);
}
}
你没有打电话matches
或find
上匹配。它没有做任何工作。
getGroupCount
是错误的调用方法。您的正则表达式没有捕获组,即使有捕获组,也不会给您字符计数。
您应该使用find
,但是使用另一种正则表达式,而没有锚。我也建议您使用适当的Unicode字符类:"\\p{Lu}+"
。while (m.find())
循环使用它,并累积从m.group(0).length()
每个步骤获得的字符总数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句