热敏打印,打印小票时,需要左中右对其,而中文字符和数字及英文字符打印占的位置不同,匹配中文字符时发现网上的教程都不怎么完善,故上传一个。
protected int getChinaNum(String str) {
int amount = 0;// 创建汉字数量计数器
String exp="^[\u4E00-\u9FA5|\\!|\\,|\\。|\\(|\\)|\\《|\\》|\\“|\\”|\\?|\\:|\\;|\\【|\\】]$";
Pattern pattern=Pattern.compile(exp);
for (int i = 0; i < str.length(); i++) {// 遍历字符串每一个字符
char c = str.charAt(i);
Matcher matcher=pattern.matcher(c + "");
if(matcher.matches()) {
amount++;
}
}
return amount;
}
方法和简单,难点就是正则表达式,如有其他字符直接在exp后面添加就好 格式|\\+你想要匹配的字符。