栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

private static String regEx = "[\u4e00-\u9fa5]";

  
  private static String isChinese_Replace( String str_para )
  {
    Pattern p      = Pattern.compile( regEx );
    String str_result   = str_para;
    String str_0      = "";
    String str_1      = "";
    String str_data[]   = null;
    String str_return_reslut  = "";
    if ( str_result != null && str_result.trim().length() > 0 )
    {
      try {
 str_data = str_result.split( "" );
 for ( int i = 0; i < str_data.length; i++ )
 {
   Matcher m = p.matcher( str_data[i] );
   
   int count = 0;
   if ( m.find() )
   {
     count++;
     str_result   = m.group( 0 );
     byte[] b    = str_result.getBytes( "GBK" );
     str_0      = Integer.toHexString( b[0] );
     str_1      = Integer.toHexString( b[1] );
     str_return_reslut  = str_return_reslut + "/" + conver10( str_0 ) + conver10( str_1 ) + "/";
   } else {
     str_return_reslut = str_return_reslut + str_data[i];
   }
 }
      } catch ( NumberFormatException e ) {
 e.printStackTrace();
      } catch ( UnsupportedEncodingException e ) {
 e.printStackTrace();
      }
    } else {
      return(str_return_reslut);
    }
    return(str_return_reslut);
  }
  
  public static int conver10( String str_0 )
  {
    return(Integer.parseInt( str_0.substring( str_0.length() - 2, str_0.length() ), 16 ) );
  }

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

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;
}

最后我们附上各种字符的unicode编码的范围:
     * 汉字:[0x4e00,0x9fa5](或十进制[19968,40869])
     * 数字:[0x30,0x39](或十进制[48, 57])
     *小写字母:[0x61,0x7a](或十进制[97, 122])
     * 大写字母:[0x41,0x5a](或十进制[65, 90])

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/151105.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号