对于我的生活,我无法弄清楚为什么这个正则表达式不起作用.它应该在给定的字符串中找到大写字母并给我计数.欢迎任何想法.
这是单元测试代码:
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个问题:
"[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);
}
Run Code Online (Sandbox Code Playgroud)
更新:使用这个更简单的单行代码来计算字符串中Unicode大写字母的数量:
int countuc = testStr.split("(?=\\p{Lu})").length - 1;
Run Code Online (Sandbox Code Playgroud)
Mar*_*nik 10
你没有打电话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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30876 次 |
| 最近记录: |