如何從字串中刪除非 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP