如何打印缺少反斜杠的unicode字符的字符串?

时间:2017-01-27 12:15:08

标签: java unicode unicode-escapes

我有一个字符串如下:

  

这是字符串u00c5,在unicode字符

之前缺少斜杠

它具有unicode字符代码,但是" u"之前的所有反斜杠;不见了。如何正确打印此字符串?

我做了什么?

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

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;
}

1 个答案:

答案 0 :(得分:0)

让人惊讶。使用@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

将代码点编码为字符串并且使用正则表达式进行简单擦除无法解决问题。这不是很好,所以如果有人有另一种方式,我也会很开心。