如何从字符串中删除非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
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短