轉自:https://blog.csdn.net/zhanghan18333611647/article/details/80038629正則表達式
強烈推薦一個大神的人工智能的教程:http://www.captainbed.net/zhanghan服務器
【前言】
最近項目的短信服務對接外國的第三方發短信通道,第三方對短信內容有限制,不能含中文字符(若是含調用結果確定失敗),因此在發送以前須要對短信內容作校驗,看是否含有中文,若是含有則直接將短信發送狀態改成失敗,不用再去調用第三方;優化
【探索之旅】
站在巨人的肩膀上, 立馬在網上搜索一下關於Java怎麼判斷字符串中是否含有中文;果真網上有不少實現; 人工智能
1、實現方式一spa
一、針對每一個字符判斷.net
1 public static boolean isChinese(String str) throws UnsupportedEncodingException 2 { 3 int len = str.length(); 4 for(int i = 0;i < len;i ++) 5 { 6 String temp = URLEncoder.encode(str.charAt(i) + "", "utf-8"); 7 if(temp.equals(str.charAt(i) + "")) 8 continue; 9 String[] codes = temp.split("%"); 10 //判斷是中文仍是字符(下面判斷不精確,部分字符沒有包括) 11 for(String code:codes) 12 { 13 if(code.compareTo("40") > 0) 14 return true; 15 } 16 } 17 return false; 18 }
二、優缺點: code
a.缺點:效率低【每次都須要循環檢測字符串中每一個字符】(每次發送都須要檢測短信內容,每條內容有不少字符);blog
b.優勢:不只能檢測出中文漢字還能檢測中中文標點;教程
2、實現方式二 utf-8
一、利用正則表達式:
1 public static boolean isContainChinese(String str) { 2 3 Pattern p = Pattern.compile("[\u4e00-\u9fa5]"); 4 Matcher m = p.matcher(str); 5 if (m.find()) { 6 return true; 7 } 8 return false; 9 }
二、優缺點:
a.缺點:只能檢測出中文漢字不能檢測中文標點;
b.優勢:利用正則效率高;
3、方式三
一、改造正則
1 /** 2 * 字符串是否包含中文 3 * 4 * @param str 待校驗字符串 5 * @return true 包含中文字符 false 不包含中文字符 6 * @throws EmptyException 7 */ 8 public static boolean isContainChinese(String str) throws EmptyException { 9 10 if (StringUtils.isEmpty(str)) { 11 throw new EmptyException("sms context is empty!"); 12 } 13 Pattern p = Pattern.compile("[\u4E00-\u9FA5|\\!|\\,|\\。|\\(|\\)|\\《|\\》|\\「|\\」|\\?|\\:|\\;|\\【|\\】]"); 14 Matcher m = p.matcher(str); 15 if (m.find()) { 16 return true; 17 } 18 return false; 19 }
二、優缺點:
a.優勢:效率既高又能檢測出中文漢字和中文標點;
b.缺點:目前還沒有發現。
【總結】
一、站在巨人的肩膀上,多去查,多作比較;
二、針對程序不斷的優化,好比第一種方式循環讀字符串量大後很容易將服務器CPU搞崩。