java - 如何打印带有缺少反斜杠的unicode字符的字符串?

标签 java unicode unicode-escapes

我有一个字符串如下:

this is the string u00c5 with missing slash before unicode characters

它具有 unicode 字符代码,但缺少“u”之前的所有反斜杠。如何正确打印这个字符串?

我做了什么?

我尝试使用以下代码在不完整的 unicode 部分之前添加反斜杠。但是,replaceAll 中不允许使用 "\u$1"

public String sanitizeUnicodeQuirk(String input) {
    try {
        // String processedInput = input.replaceAll("[uU]([0123456789abcdefABCDEF]{4})", String.valueOf(Integer.parseInt("$1", 16)));    // $1 is taken literally which makes valuOf and parseInt useless
        String processedInput = input.replaceAll("[uU]([0123456789abcdefABCDEF]{4})", "\\\\u$1");    // Cannot make "\u$1"
        String newInput = new String(processedInput.getBytes(), "UTF-8");
        return newInput;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return input;
}

最佳答案

哎呀。使用 @AlastairMcCormack 在评论中提供的可能重复链接进行概念证明:

public class Test {
    public static void main(String[] args) {
        String input = "this is the string u0075u0031u0032u0033u0034 with missing slash before unicode characters";
        System.out.println("Original input: " + input);
        Pattern pattern = java.util.regex.Pattern.compile("[uU][0-9a-fA-F]{4}");
        Matcher matcher = pattern.matcher(input);
        StringBuilder builder = new StringBuilder();
        int lastIndex = 0;
        while (matcher.find()) {
               String codePoint = matcher.group().substring(1);
               System.out.println("Found code point: " + codePoint);
               Character charSymbol = (char) Integer.parseInt(codePoint, 16);
               builder.append(input.substring(lastIndex, matcher.start()) + charSymbol);
               lastIndex = matcher.end();
        }
        builder.append(input.substring(lastIndex));
        System.out.println("Modded input: " + builder.toString());
    }
}

产量:

Original input: this is the string u0075u0031u0032u0033u0034 with missing slash before unicode characters
Found code point: 0075
Found code point: 0031
Found code point: 0032
Found code point: 0033
Found code point: 0034
Modded input: this is the string u1234 with missing slash before unicode characters

代码点被编码为字符串确实有意义,并且使用正则表达式进行任何简单的清理都无法解决这个问题。这不太漂亮,所以如果有人有其他方法,我也会很高兴。

关于java - 如何打印带有缺少反斜杠的unicode字符的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41893798/

相关文章:

java - 无法使用 jackson 库匹配包含正斜杠 (/) 的节点

java - 将 unicode 文字字符串打印为 Unicode 字符

java - 使用 Java 参数化类型和多态性实现这种通用编程场景的方法

java - 将托管 bean 转换为 EJB

python - 如何使用 Python 将具有 cp1252 字符的 unicode 字符串转换为 UTF-8?

python - 如何知道 Unicode 标识符是否有效?

scala - 将特殊字符转换为 Unicode 转义字符 Scala

java - 带点的属性名称 Jackson JSON 解析

java - emma是否支持多个进程并发写入 session 文件?

c++ - 将 std::string 中的迭代字符与 unicode C++ 进行比较