今天和同事在討論一個問題,需要檢查“輸入的字符串中是否包含中文”,剛開始想到是用正則表達式,正則表達式中是以[u4e00-u9fa5]來全匹配字符是否是中文,但現在面臨的問題是這個字符串中還可能包含英文字符、數字、特殊字符,一時也沒想出能匹配該場景的正則表達式,后來在網上搜了下,可以使用Matcher類來解決該問題,大致的代碼實現如下:
- 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;
- }