如何在Java String中用\ u替换\\ u

时间:2012-04-05 20:55:57

标签: java string unicode unicode-string

我有一个格式的字符串:

  

“AAA \\ u2022bbb \\ u2014ccc”

我想显示两个特殊的字符,但为了能够做到这一点,我必须先将字符串转换为这种格式:

  

“AAA \ u2022bbb \ u2014ccc”

我试过写这个,但它给出了编译错误:

String encodedInput = input.replace("\\u", "\u");

这必须是直截了当的,但我无法得到它。有什么想法吗?

5 个答案:

答案 0 :(得分:4)

不幸的是我不知道某种评估。

    String s = "aaa\\u2022bbb\\u2014ccc";
    StringBuffer buf = new StringBuffer();
    Matcher m = Pattern.compile("\\\\u([0-9A-Fa-f]{4})").matcher(s);
    while (m.find()) {
        try {
            int cp = Integer.parseInt(m.group(1), 16);
            m.appendReplacement(buf, "");
            buf.appendCodePoint(cp);
        } catch (NumberFormatException e) {
        }
    }
    m.appendTail(buf);
    s = buf.toString();

答案 1 :(得分:3)

除了逃避逃脱 - 正如其他人(例如barsju)所指出的那样 - 您还必须考虑通常将\uNNNN表示法转换为实际的Unicode字符由Java编译器完成在编译时。

因此,即使你解决了反斜杠转义问题,你也可能更难以显示实际的Unicode字符,因为你似乎是在运行时而不是在编译时操作字符串。

This answer提供了一种方法,用实际对应的Unicode字符替换运行时字符串中的\uNNNN转义序列。请注意,该方法在错误处理,边界检查和意外输入方面留下了一些TODO。

(编辑:我认为这里提供的例如dash1e的基于正则表达式的解决方案将比我链接的方法更好,因为它们在处理意外的输入数据方面更加精致。)

答案 2 :(得分:2)

尝试

Pattern unicode = Pattern.compile("\\\\u(.{4})");
Matcher matcher = unicode.matcher("aaa\\u2022bbb\\u2014ccc");
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
    int code = Integer.parseInt(matcher.group(1), 16);
    matcher.appendReplacement(sb, new String(Character.toChars(code)));
}
matcher.appendTail(sb);
System.out.println(sb.toString());

答案 3 :(得分:0)

你需要逃脱逃脱:

System.out.println("aaa\\u2022bbb\\u2014ccc".replace("\\\\u", "\\u"));

答案 4 :(得分:0)

String input = "aaa\\u2022bbb\\u2014ccc";
String korv = input.replace("\\\\u", "\\u");
System.out.println(korv);

=>

aaa\u2022bbb\u2014ccc

这是因为“\”是字符串中的特殊字符,因此您也需要引用它。 “\”==“\”。