Java正则统计数字,java使用正则表达式实现字数统计

@Override

public CalculateWordCountDTO calculateWordCount(String str) throws ServiceException {

CalculateWordCountDTO rtn = new CalculateWordCountDTO();

int wordCount = 0;

int characterCount = 0;

int chineseCount = 0;

int englishLetterCount = 0;

int figureCount = 0;

int spaceCount = 0;

int symbolCount = 0;

int lineCount = 0;

try {

do {

if (ValidateUtils.isNullOrEmpty(str)) {

rtn.setCharacterCount(characterCount)

.setChineseCount(chineseCount)

.setEnglishLetterCount(englishLetterCount)

.setFigureCount(figureCount)

.setSpaceCount(spaceCount)

.setSymbolCount(symbolCount)

.setWordCount(wordCount)

.setLineCount(lineCount);

break;

}

boolean lineFlag = false;

wordCount = str.length();

for (int i = 0; i < str.length(); i++) {

String tempStr = str.substring(i, i + 1);

String pattern = "\\r";

if (Pattern.matches(pattern, tempStr)) {

lineCount++;

lineFlag = true;

continue;

}

pattern = "\\n";

if (Pattern.matches(pattern, tempStr)) {

if (!lineFlag) {

lineCount++;

lineFlag = false;

}

continue;

}

characterCount += tempStr.getBytes("GBK").length;

if (isChinese(tempStr)) {

chineseCount++;

} else if (isEnglishLetter(tempStr)) {

englishLetterCount++;

} else if (isFigure(tempStr)) {

figureCount++;

} else if (isSpace(tempStr)) {

spaceCount++;

} else {

symbolCount++;

}

}

rtn.setCharacterCount(characterCount)

.setChineseCount(chineseCount)

.setEnglishLetterCount(englishLetterCount)

.setFigureCount(figureCount)

.setSpaceCount(spaceCount)

.setSymbolCount(symbolCount)

.setWordCount(wordCount-lineCount)

.setLineCount(lineCount);

} while (false);

} catch (Exception e) {

throw new ServiceException(e, ErrorCodeEnum.UNKNOWN.getErrorCode());

}

return rtn;

}

/***

* 判断字符是否为中文

* @param str 需要判断的字符

* @return 中文返回true,非中文返回false

*/

private boolean isChinese(String str) {

String pattern = "^[\\u4E00-\\u9FA5]+$";

return Pattern.matches(pattern, str);

}

/***

* 判断字符是否为英文字母

* @param str 需要判断的字符

*/

private boolean isEnglishLetter(String str) {

String pattern = "^[a-zA-Z]+$";

return Pattern.matches(pattern, str);

}

/***

* 判断字符是否为数字

* @param str 需要判断的字符

*/

private boolean isFigure(String str) {

String pattern = "^[0-9]+$";

return Pattern.matches(pattern, str);

}

/***

* 判断字符是否为空格

* @param str 需要判断的字符

*/

private boolean isSpace(String str) {

String pattern = "\\s";

return Pattern.matches(pattern, str);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值