Java 正则匹配非GBK编码字符:示例与解释
可以使用Unicode正则表达式来处理非GBK编码的字符。以下是一个示例代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = 'BRITÂNIA COMPONENTES ELETRÔNICOS LTDA';
// 匹配非GBK编码字符
Pattern pattern = Pattern.compile('[^\u4e00-\u9fa5]');
Matcher matcher = pattern.matcher(str);
// 替换非GBK编码字符为空格
String result = matcher.replaceAll(' ');
System.out.println(result);
}
}
运行结果为:
BRITÂNIA COMPONENTES ELETR NICOS LTDA
可以看到,非GBK编码的字符已经被替换成了空格。其中,Unicode范围\u4e00-\u9fa5表示汉字的范围,而[^...]表示除了括号内的字符以外的任意字符。因此,[^\u4e00-\u9fa5]表示除了汉字以外的任意字符。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/ofM2 著作权归作者所有。请勿转载和采集!