从文件中读取十六进制 Unicode 字符串并将其转换为 Java 字符串?

Reading hexadecimal Unicode String from file and turn it into Java String?

我目前正在为 JSON 文档编写一个小解析器。 UTF 字符可以表示为\u0628

如何将字符串 \u0628 转换为真正的 Java 字符?

你可以使用这样一段代码:

String str = myString.split(" ")[0];
str = str.replace("\","");
String[] arr = str.split("u");
String text = "";
for(int i = 1; i < arr.length; i++){
    int hexVal = Integer.parseInt(arr[i], 16);
    text += (char)hexVal;
}

或者您可以使用 Apache Commons Lang:

import org.apache.commons.lang.StringEscapeUtils;

@Test
public void testUnescapeJava() {
    String sJava="\u0048\u0065\u006C\u006C\u006F";
    System.out.println("StringEscapeUtils.unescapeJava(sJava):\n" + StringEscapeUtils.unescapeJava(sJava));
}


 output:
 StringEscapeUtils.unescapeJava(sJava):
 Hello

您可以使用 UTF_16 字符集解析字节:

例如

byte[] data = {0x06, 0x28};
String string = new String(data, StandardCharsets.UTF_16);

您可以使用正则表达式找到转义符

private static Pattern ESCAPE_PATTERN = Pattern.compile("\\u([0-9a-fA-F]{2})([0-9a-fA-F]{2})");

public static String replaceCharEscapes(String input) {
    Matcher m = ESCAPE_PATTERN.matcher(input);
    if (!m.find()) {
        return input;
    }
    StringBuilder outputBuilder = new StringBuilder(input.subSequence(0, m.start()));
    int lastEnd = m.end();
    outputBuilder.append(getChar(m));

    while (m.find()) {
        outputBuilder.append(input.subSequence(lastEnd, m.start()))
                .append(getChar(m));
        lastEnd = m.end();
    }

    if (lastEnd != input.length()) {
        outputBuilder.append(input.subSequence(lastEnd, input.length()));
    }

    return outputBuilder.toString();
}

private static String getChar(Matcher m) {
    return new String(new byte[] {
        Byte.parseByte(m.group(1), 16),
        Byte.parseByte(m.group(2), 16),
    });
}

示例:

replaceCharEscapes("\u0043:\\u0050\u0072\u006f\u0067\u0072\u0061\u006ds")

returns C:\Programs