java 返回字符串中汉字的个数

public static int GetHanNumFromString(String str) {
int count = 0;
String regEx = "[\u4e00-\u9fa5]";
Pattern p = Pattern.compile(regEx);//①
Matcher m = p.matcher(str);//②
//boolean b=m.matches();//可判断是否符合正则表达式条件
  //进行累计汉字数量
while (m.find()) {
for (int i = 0; i <= m.groupCount(); i++) {
count++;
}
}
return count;
}

补充说明:
指定为字符串的正则表达式必须首先被编译为此类的实例。(①)
然后,可将得到的模式用于创建 Matcher 对象,依照正则表达式,该对象可以与任意字符序列匹配。(②)
执行匹配所涉及的所有状态都驻留在匹配器中,所以多个匹配器可以共享同一模式。

Pattern类详解见:https://blog.csdn.net/demon7552003/article/details/94884761




原文地址:https://www.cnblogs.com/wnnstudy/p/13723808.html