Java determines whether the string contains a Chinese method

  • 2020-04-01 03:21:35
  • OfStack

Today and his colleagues are discussing a problem, need to check the "input" if the string contains Chinese, at first thought is to use regular expressions, in the regular expression is [u4e00 - u9fa5] to the whole character is Chinese, but now are faced with the problem may also be included in the string is English characters, Numbers, special character, also can't come up with to match the scene of a regular expression, then searched on the Internet, you can use the Matcher class to solve the problem, roughly code implementation is as follows:


import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class demo {
static String regEx = "[u4e00-u9fa5]";
static Pattern pat = Pattern.compile(regEx);
public static void main(String[] args) {
String input = "Hell world!";
System.out.println(isContainsChinese(input));
input = "hello world";
System.out.println(isContainsChinese(input));
}
 
public static boolean isContainsChinese(String str)
{
Matcher matcher = pat.matcher(str);
boolean flg = false;
if (matcher.find())    {
flg = true;
}
return flg;
}


Related articles: