Java判断字符串中是否存在汉字

algorain

Java对汉字的支持还是很好的(好像除了python,其他都挺好),这次分享一段关于如何判断字符串中是否有汉字的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.rain.demo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class validate_haven {
public static void main(String[] args) {
String string = "中国";
boolean result = isHave_validate(string);
System.out.println(result);
}
public static boolean isHave_validate(String str) {
boolean flag = true;
int count = 0;
String regEx = "[\\u4e00-\\u9fa5]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
while (m.find()) {
for (int i = 0; i <= m.groupCount(); i++) {
count = count + 1;
}
}
if (count == 0) {
flag = false;
}
return flag;
}


}

  • Title: Java判断字符串中是否存在汉字
  • Author: algorain
  • Created at: 2017-02-06 10:23:41
  • Updated at: 2023-05-14 21:39:50
  • Link: http://www.rain1024.com/2017/02/06/java-article28/
  • License: This work is licensed under CC BY-NC-SA 4.0.
 Comments