Today, I was discussing a problem with my colleagues. We need to check "whether the input string contains Chinese characters." At first, I thought of using regular expressions. The regular expression uses [u4e00-u9fa5] to fully match whether the characters are Chinese, but The problem we are facing now is that this string may also contain English characters, numbers, and special characters. I couldn’t think of a regular expression that could match this scenario. Later, I searched online and found that the Matcher class can be used to solve this problem. The rough 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;}