Home  >  Article  >  Java  >  How does Java determine whether a string contains Chinese characters and filter Chinese characters?

How does Java determine whether a string contains Chinese characters and filter Chinese characters?

黄舟
黄舟Original
2017-09-08 10:56:132009browse

This article mainly introduces in detail java to determine whether a string contains Chinese characters and filter out Chinese characters. It has certain reference value. Interested friends can refer to

java to determine characters. Whether the string contains Chinese and filter out Chinese, the specific content is as follows

1. Determine whether the string contains Chinese method encapsulation


/**
 * 判断字符串中是否包含中文
 * @param str
 * 待校验字符串
 * @return 是否为中文
 * @warn 不能校验是否为中文标点符号 
 */
public static boolean isContainChinese(String str) {
 Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
 Matcher m = p.matcher(str);
 if (m.find()) {
  return true;
 }
 return false;
}

Note: Need to import

import java.util.regex.Matcher;
import java.util.regex.Pattern;

##2. Filter Chinese


/**
 * 过滤掉中文
 * @param str 待过滤中文的字符串
 * @return 过滤掉中文后字符串
 */
public static String filterChinese(String str) {
 // 用于返回结果
 String result = str;
 boolean flag = isContainChinese(str);
 if (flag) {// 包含中文
  // 用于拼接过滤中文后的字符
  StringBuffer sb = new StringBuffer();
  // 用于校验是否为中文
  boolean flag2 = false;
  // 用于临时存储单字符
  char chinese = 0;
  // 5.去除掉文件名中的中文
  // 将字符串转换成char[]
  char[] charArray = str.toCharArray();
  // 过滤到中文及中文字符
  for (int i = 0; i < charArray.length; i++) {
   chinese = charArray[i];
   flag2 = isChinese(chinese);
   if (!flag2) {// 不是中日韩文字及标点符号
    sb.append(chinese);
   }
  }
  result = sb.toString();
 }
 return result;
}

Description: isChinese(char) method, see article: java Chinese and special character verification

3. Test


public static void main(String[] args) {
 String fileName = "test,中文";
 System.out.println(filterChinese(fileName));
}

The above is the detailed content of How does Java determine whether a string contains Chinese characters and filter Chinese characters?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn