首页 > 开发 > Java > 正文

java实现检测是否字符串中包含中文

2024-07-13 09:55:55
字体:
来源:转载
供稿:网友

本文给大家分享了2个使用java检测字符串中是否包含中文的代码,都非常的实用,最后附上了各种字符的unicode编码的范围,方便我们以后使用正则进行匹配检测。

代码非常实用,这里就不错废话,直接奉上

主要功能是实现判断字符串是否包含汉字 并且替换成ASCLL

 

 
  1. private static String regEx = "[//u4e00-//u9fa5]"
  2.  
  3. /** 
  4. * 判断字符串是否包含汉字 并且替换成ASCLL 
  5. * 
  6. * @param str_para 
  7. * @return str_result 
  8. */ 
  9. private static String isChinese_Replace( String str_para ) 
  10. Pattern p = Pattern.compile( regEx ); 
  11. String str_result = str_para; 
  12. String str_0 = ""
  13. String str_1 = ""
  14. String str_data[] = null
  15. String str_return_reslut = ""
  16. if ( str_result != null && str_result.trim().length() > 0 ) 
  17. try { 
  18. str_data = str_result.split( "" ); 
  19. for ( int i = 0; i < str_data.length; i++ ) 
  20. Matcher m = p.matcher( str_data[i] ); 
  21. /* L.d(str_data[i]); */ 
  22. int count = 0; 
  23. if ( m.find() ) 
  24. count++; 
  25. str_result = m.group( 0 ); 
  26. byte[] b = str_result.getBytes( "GBK" ); 
  27. str_0 = Integer.toHexString( b[0] ); 
  28. str_1 = Integer.toHexString( b[1] ); 
  29. str_return_reslut = str_return_reslut + "/" + conver10( str_0 ) + conver10( str_1 ) + "/"
  30. else { 
  31. str_return_reslut = str_return_reslut + str_data[i]; 
  32. catch ( NumberFormatException e ) { 
  33. e.printStackTrace(); 
  34. catch ( UnsupportedEncodingException e ) { 
  35. e.printStackTrace(); 
  36. else { 
  37. return(str_return_reslut); 
  38. return(str_return_reslut); 
  39. /* 字符串转换十进制 */ 
  40. public static int conver10( String str_0 ) 
  41. return(Integer.parseInt( str_0.substring( str_0.length() - 2, str_0.length() ), 16 ) ); 

我们来看个稍微简单些的代码,一些需求不高的地方可以用到

 

 
  1. import java.util.regex.Matcher; 
  2. import java.util.regex.Pattern; 
  3. public class demo { 
  4. static String regEx = "[/u4e00-/u9fa5]"
  5. static Pattern pat = Pattern.compile(regEx); 
  6. public static void main(String[] args) { 
  7. String input = "Hell world!"
  8. System.out.println(isContainsChinese(input)); 
  9. input = "hello world"
  10. System.out.println(isContainsChinese(input)); 
  11.  
  12. public static boolean isContainsChinese(String str) 
  13. Matcher matcher = pat.matcher(str); 
  14. boolean flg = false
  15. if (matcher.find()) { 
  16. flg = true
  17. return flg; 

最后我们附上各种字符的unicode编码的范围:

* 汉字:[0x4e00,0x9fa5](或十进制[19968,40869])

* 数字:[0x30,0x39](或十进制[48, 57])

*小写字母:[0x61,0x7a](或十进制[97, 122])

* 大写字母:[0x41,0x5a](或十进制[65, 90])

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表