如何从字符串中删除非ASCII字符
Posix字符类\p{ASCII} 与ASCII字符匹配,而元字符^用作负数。
即以下表达式匹配所有非ASCII字符。
"[^\\p{ASCII}]"replaceAll()String类的方法接受正则表达式和替换字符串,并用指定的替换字符串替换当前字符串的字符(匹配给定的模式)。
因此,您可以使用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("输入输入数据:");
String input = sc.nextLine();
String result = input.replaceAll(regex, "");
System.out.println("Result: "+result);
}
}输出结果
输入输入数据: 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}]";
//创建一个模式对象
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("Result: \n"+ sb.toString() );
}
}输出结果
Enter input string: whÿ do we fall Result: wh do we fall
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短