逃脱unicode代理人物?

时间:2014-04-07 20:02:46

标签: java unicode escaping unicode-escapes

我有以下文本行(请参阅代码:

TEXT

我正在尝试做的是将表情符号(电话图标)转换为两个\ u字符然后回到其原始电话图标?下面的第一种方法工作正常但我基本上想要通过一个范围来逃避,这样我就可以逃避任何这样的字符。我不知道如何使用下面的第一种方法。

如何使用UnicodeEscaper作为与StringEscapeUtils相同的输出来实现这个基于范围的转义(即转到两个\ uxx \ uxx然后转换回电话图标)?

import org.apache.commons.lang3.text.translate.UnicodeEscaper;
import org.apache.commons.lang3.text.translate.UnicodeUnescaper;

    String text = "Unicode surrogate here-> <--here";
    // escape the entire string...not what I want because there could
    // be \n \r or any other escape chars that I want left in tact (i just want  a range)
    String text2 = org.apache.commons.lang.StringEscapeUtils.escapeJava(text);
    System.out.println(text2);   // "Unicode surrogate here-> \uD83D\uDCF1<--here"
    // unescape it back to the phone emoticon
    text2 = org.apache.commons.lang.StringEscapeUtils.unescapeJava(text);
    System.out.println(text2); // "Unicode surrogate here-> <--here"

    // How do I do the same as above but but looking for a range of chars to escape (i.e. any unicode surrogate)
    // , which is what i want  and not to escape the entire string
    text2 = UnicodeEscaper.between(0x10000, 0x10FFFF).translate(text);
    System.out.println(text2); // "Unicode surrogate here-> \u1F4F1<--here"
    // unescape .... (need the phone emoticon here)
    text2 = (new UnicodeUnescaper().translate(text2));
    System.out.println(text2);// "Unicode surrogate here-> ὏1<--here"

2 个答案:

答案 0 :(得分:3)

回答太迟了。但我发现你需要

org.apache.commons.lang3.text.translate.JavaUnicodeEscaper

类而不是UnicodeEscaper。

使用它,打印:

Unicode surrogate here-> \uD83D\uDCF1<--here

unescaping效果很好。

答案 1 :(得分:2)

你的字符串:

"Unicode surrogate here-> \u1F4F1<--here"

不符合你的想法。

char基本上是UTF-16代码单元,因此是16位。那么这里发生的是你有\u1f41 1;这解释了你的输出。

我不知道你叫什么&#34;逃避&#34;在这里,但如果这是替换代理人对,请查看Character.toChars()。它将返回表示一个Unicode代码点所必需的char序列,无论它是否在BMP(一个字符)中(不是两个字符)。

对于代码点U + 1f4f1,它将返回一个包含字符0xd83d和0xdcf1的双元素char数组。这就是你想要的。

相关问题