【问题标题】:StringEscapeUtils: How to unescape a string except emoji?StringEscapeUtils:如何对除表情符号之外的字符串进行转义?
【发布时间】:2017-09-03 08:44:11
【问题描述】:
【问题讨论】:
标签:
java
apache-commons-lang3
【解决方案1】:
“完全取消转义”字符串可能更容易,然后仅重新转义表情符号。您可以通过使用Character.isLowSurrogate 和Character.isHighSurrogate 检测代理对字符来做到这一点。
例如:
StringBuilder sb = new StringBuilder(str.length());
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
if (Character.isHighSurrogate(c) || Character.isLowSurrogate(c)) {
// Append the escaped character.
sb.append("\\u");
sb.append(String.format("%04x", (int) c));
} else {
// Append the character as-is.
sb.append(c);
}
}
String partlyEscaped = sb.toString();
Ideone demo