如何从字符串中删除非 ASCII 字符


Posix 字符类 \p{ASCII} 匹配 ASCII 字符和元字符 ^ 充当否定。

即,以下表达式匹配所有非 ASCII 字符。

"[^\p{ASCII}]"

String 类的 replaceAll() 方法接受正则表达式和替换字符串,并使用指定的替换字符串替换当前字符串(匹配给定模式)中的字符。

因此,你可以使用 replaceAll() 方法将匹配的字符替换为“”,从而将其删除。

示例 1

import java.util.Scanner;
public class Exp {
   public static void main( String args[] ) {
      Scanner sc = new Scanner(System.in);
      String regex = "[^\p{ASCII}]";
      System.out.println("Enter input data:");
      String input = sc.nextLine();
      String result = input.replaceAll(regex, "");
      System.out.println("Result: "+result);
   }
}

输出

Enter input data:
whÿ do we fall
Result: wh do we fall

示例 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main( String args[] ) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string: ");
      String input = sc.nextLine();
      String regex = "[^\p{ASCII}]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      //Creating an empty string buffer
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {
         matcher.appendReplacement(sb, "");
      }
      matcher.appendTail(sb);
      System.out.println("Result: \n"+ sb.toString() );
   }
}

输出

Enter input string:
whÿ do we fall
Result:
wh do we fall

更新于:2019 年 11 月 21 日

1 千+ 次浏览

提升您的职业生涯

完成该课程获得认证

开始使用
广告
© . All rights reserved.