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

javaobject oriented programmingprogramming更新于 2024/5/13 0:44:17

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

输出

Enter input data:
whÿ do we fall
结果: 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("输入输入字符串: ");
      String input = sc.nextLine();
      String regex = "[^\p{ASCII}]";
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex);
      //匹配字符串中的编译模式
      Matcher matcher = pattern.matcher(input);
      //创建一个空的字符串缓冲区
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {
         matcher.appendReplacement(sb, "");
      }
      matcher.appendTail(sb);
      System.out.println("结果: \n"+ sb.toString() );
   }
}

输出

输入输入字符串:
whÿ do we fall
结果:
wh do we fall

相关文章


有用资源