首页 > 代码库 > Java 完美判断中文字符

Java 完美判断中文字符

Java判断一个字符串是否有中文一般情况是利用Unicode编码(CJK统一汉字的编码区间:0x4e00–0x9fbb)的正则来做判断,但是其实这个区间来判断中文不是非常精确,因为有些中文的标点符号比如:,。等等是不能识别的。

以下是比较完善的判断方法:CharUtil.java

http://www.micmiu.com/lang/java/java-check-chinese/ 

 1 import java.util.regex.Pattern; 2  3 public class CharUtil { 4  5     public static void main(String[] args) { 6         String[] strArr = new String[] { "www.micmiu.com", 7                 "!@#$%^&*()_+{}[]|\"‘?/:;<>,.", "!¥……()——:;“”‘’《》,。?、", "不要啊", 8                 "やめて", "韩佳人", "???" }; 9         for (String str : strArr) {10             System.out.println("===========> 测试字符串:" + str);11             System.out.println("正则判断结果:" + isChineseByREG(str) + " -- "12                     + isChineseByName(str));13             System.out.println("Unicode判断结果 :" + isChinese(str));14             System.out.println("详细判断列表:");15             char[] ch = str.toCharArray();16             for (int i = 0; i < ch.length; i++) {17                 char c = ch[i];18                 System.out.println(c + " --> " + (isChinese(c) ? "是" : "否"));19             }20         }21     }22 23     // 根据Unicode编码完美的判断中文汉字和符号24     private static boolean isChinese(char c) {25         Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);26         if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS27                 || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS28                 || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A29                 || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B30                 || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION31                 || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS32                 || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {33             return true;34         }35         return false;36     }37 38     // 完整的判断中文汉字和符号39     public static boolean isChinese(String strName) {40         char[] ch = strName.toCharArray();41         for (int i = 0; i < ch.length; i++) {42             char c = ch[i];43             if (isChinese(c)) {44                 return true;45             }46         }47         return false;48     }49 50     // 只能判断部分CJK字符(CJK统一汉字)51     public static boolean isChineseByREG(String str) {52         if (str == null) {53             return false;54         }55         Pattern pattern = Pattern.compile("[\\u4E00-\\u9FBF]+");56         return pattern.matcher(str.trim()).find();57     }58 59     // 只能判断部分CJK字符(CJK统一汉字)60     public static boolean isChineseByName(String str) {61         if (str == null) {62             return false;63         }64         // 大小写不同:\\p 表示包含,\\P 表示不包含65         // \\p{Cn} 的意思为 Unicode 中未被定义字符的编码,\\P{Cn} 就表示 Unicode中已经被定义字符的编码66         String reg = "\\p{InCJK Unified Ideographs}&&\\P{Cn}";67         Pattern pattern = Pattern.compile(reg);68         return pattern.matcher(str.trim()).find();69     }70 }