黑马程序员技术交流社区

标题: 如何将在一段混乱的字符串中提取中文? [打印本页]

作者: 冰霜之卅    时间: 2015-9-22 23:33
标题: 如何将在一段混乱的字符串中提取中文?
比如说“sdsd王434g二3425小gdgs”
得到   王二小
作者: meihua    时间: 2015-9-23 07:19
遍历,判断?
空格,数字 ,字母都有对应的ASCII码,不在这些范围内就提取出来
作者: pegasus    时间: 2015-9-23 10:11
  1. String strr = "swsdnboin王O*Uoamsonmjd9adxn晓lcancd323五";
  2. String str1 = "";
  3. for (int i = 0; i < strr.length(); i++) {
  4.         if (strr.substring(i, i + 1).getBytes().length == 2) {
  5.                 str1 = str1 + strr.substring(i, i + 1);
  6.         }
  7. }
  8. System.out.println(str1);
复制代码

作者: pegasus    时间: 2015-9-23 10:15
  1. public static void main(String[] args) {
  2.         String regEx1 = "[\\u4e00-\\u9fa5]";
  3.         String str = "1 2fdAsz我是hhhZ大傻";
  4.         String s1 = matchResult(Pattern.compile(regEx1), str);
  5.         System.out.println(s1);
  6. }

  7. public static String matchResult(Pattern p, String str) {
  8.         StringBuilder sb = new StringBuilder();
  9.         Matcher m = p.matcher(str);
  10.         while (m.find())
  11.                 for (int i = 0; i <= m.groupCount(); i++) {
  12.                         sb.append(m.group());
  13.                 }
  14.         return sb.toString();
  15. }
复制代码

作者: pegasus    时间: 2015-9-23 10:20
  1. String str = "123abc中文cde123abc提取123ab我ABC汉DEF和我们678,854中华人民共和国,美国";
  2. Pattern pattern = null;
  3. Matcher matcher = null;
  4. String value = null;
  5. pattern = Pattern.compile("([\u4e00-\u9fa5]+)");
  6. matcher = pattern.matcher(str);
  7. while (matcher.find()) {
  8.         value = matcher.group(0);
  9.         System.out.print(value);
  10. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2