Java判斷字符串中是否包含中文方法
今天和同事在討論一個(gè)問題,需要檢查“輸入的字符串中是否包含中文”,剛開始想到是用正則表達(dá)式,正則表達(dá)式中是以[u4e00-u9fa5]來全匹配字符是否是中文,但現(xiàn)在面臨的問題是這個(gè)字符串中還可能包含英文字符、數(shù)字、特殊字符,一時(shí)也沒想出能匹配該場(chǎng)景的正則表達(dá)式,后來在網(wǎng)上搜了下,可以使用Matcher類來解決該問題,大致的代碼實(shí)現(xiàn)如下:
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; }
相關(guān)文章

舉例講解Java編程中this關(guān)鍵字與super關(guān)鍵字的用法

IDEA整合SSM框架實(shí)現(xiàn)網(wǎng)頁(yè)上顯示數(shù)據(jù)

簡(jiǎn)單了解Spring Web相關(guān)模塊運(yùn)行原理