java转换emoji表情

/**
* @Description 将字符串中的emoji表情转换成可以在utf-8字符集数据库中保存的格式(表情占4个字节,需要utf8mb4字符集)
* @param str
* 待转换字符串
* @return 转换后字符串
* @throws UnsupportedEncodingException
* exception
*/
public static String emojiConvert1(String str)
throws UnsupportedEncodingException {
String patternString = "([\\x{10000}-\\x{10ffff}\ud800-\udfff])";

Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(str);
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
try {
matcher.appendReplacement(
sb,
"[["
+ URLEncoder.encode(matcher.group(1),
"UTF-8") + "]]");
} catch(UnsupportedEncodingException e) {
LOG.error("emojiConvert error", e);
throw e;
}
}
matcher.appendTail(sb);
LOG.debug("emojiConvert " + str + " to " + sb.toString()
+ ", len:" + sb.length());
return sb.toString();
}

/**
* @Description 还原utf8数据库中保存的含转换后emoji表情的字符串
* @param str
* 转换后的字符串
* @return 转换前的字符串
* @throws UnsupportedEncodingException
* exception
*/
public static String emojiRecovery2(String str)
throws UnsupportedEncodingException {
String patternString = "\\[\\[(.*?)\\]\\]";

Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(str);

StringBuffer sb = new StringBuffer();
while(matcher.find()) {
try {
matcher.appendReplacement(sb,
URLDecoder.decode(matcher.group(1), "UTF-8"));
} catch(UnsupportedEncodingException e) {
LOG.error("emojiRecovery error", e);
throw e;
}
}
matcher.appendTail(sb);
LOG.debug("emojiRecovery " + str + " to " + sb.toString());
return sb.toString();
}

转载于:https://www.cnblogs.com/shihaiming/p/5833244.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值