gpt4 book ai didi

java - 如何验证 UTF-8 字符串是否包含错误编码的字符

转载 作者:太空狗 更新时间:2023-10-29 22:32:39 27 4
gpt4 key购买 nike

在大型数据集中,我有一些数据如下所示:

"guide (but, yeah, it’s okay to share it with ‘em)."

我在十六进制编辑器中打开文件并通过字符编码检测算法 ( http://code.google.com/p/juniversalchardet/ ) 运行原始字节数据,它被肯定地检测为 UTF-8。

在我看来,数据源错误地解释了原始字符集,并将有效的 UTF-8 写入了我收到的输出。

我想尽我所能验证数据。是否有任何启发式/算法可以帮助我尝试验证?

最佳答案

一旦你有了字符串,你就不能这样做了,你必须在你仍然有原始输入的时候这样做。一旦你有了字符串,没有一些非常脆弱的测试,就没有办法自动判断 ' 是否真的是预期的输入。例如:

public static boolean isUTF8MisInterpreted( String input ) {
//convenience overload for the most common UTF-8 misinterpretation
//which is also the case in your question
return isUTF8MisInterpreted( input, "Windows-1252");
}

public static boolean isUTF8MisInterpreted( String input, String encoding) {

CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
CharsetEncoder encoder = Charset.forName(encoding).newEncoder();
ByteBuffer tmp;
try {
tmp = encoder.encode(CharBuffer.wrap(input));
}

catch(CharacterCodingException e) {
return false;
}

try {
decoder.decode(tmp);
return true;
}
catch(CharacterCodingException e){
return false;
}
}

public static void main(String args[]) {
String test = "guide (but, yeah, it’s okay to share it with ‘em).";
String test2 = "guide (but, yeah, it’s okay to share it with ‘em).";
System.out.println( isUTF8MisInterpreted(test)); //true
System.out.println( isUTF8MisInterpreted(test2)); //false

}

如果您仍然可以访问原始输入,您可以通过以下方式查看字节数组是否相当于完全有效的 utf-8 字节序列:

public static boolean isValidUTF8( byte[] input ) {

CharsetDecoder cs = Charset.forName("UTF-8").newDecoder();

try {
cs.decode(ByteBuffer.wrap(input));
return true;
}
catch(CharacterCodingException e){
return false;
}
}

您还可以将 CharsetDecoder 与流一起使用,默认情况下,它会在给定编码中看到无效字节时立即抛出异常。

关于java - 如何验证 UTF-8 字符串是否包含错误编码的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14236923/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com