对于我的生活,我无法弄清楚为什么这个正则表达式不起作用.它应该在给定的字符串中找到大写字母并给我计数.欢迎任何想法.
这是单元测试代码:
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); } }
anubhava.. 17
它不起作用,因为你有2个问题:
正则表达式不正确,它应该是"[A-Z]"
ASCII字母或\p{Lu}
Unicode大写字母
你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;
Marko Topoln.. 10
你没有打电话matches
或find
在匹配上.它没有做任何工作.
getGroupCount
是一种错误的调用方法.你的正则表达式没有捕获组,即使它没有,它也不会给你字符数.
你应该使用find
,但使用不同的正则表达式,没有锚点.我还建议使用正确的Unicode字符类:"\\p{Lu}+"
.在while (m.find())
循环中使用它,并累计从m.group(0).length()
每一步获得的字符总数.
你没有打电话matches
或find
在匹配上.它没有做任何工作.
getGroupCount
是一种错误的调用方法.你的正则表达式没有捕获组,即使它没有,它也不会给你字符数.
你应该使用find
,但使用不同的正则表达式,没有锚点.我还建议使用正确的Unicode字符类:"\\p{Lu}+"
.在while (m.find())
循环中使用它,并累计从m.group(0).length()
每一步获得的字符总数.
这应该做你想要的,
@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); }
它不起作用,因为你有2个问题:
正则表达式不正确,它应该是"[A-Z]"
ASCII字母或\p{Lu}
Unicode大写字母
你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;