|
|
@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
package com.luoo.user.util;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import java.io.UnsupportedEncodingException;
|
|
|
|
|
|
|
|
import java.net.URLDecoder;
|
|
|
|
|
|
|
|
import java.net.URLEncoder;
|
|
|
|
|
|
|
|
import java.util.regex.Matcher;
|
|
|
|
|
|
|
|
import java.util.regex.Pattern;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public class EmojiConverterUtil {
|
|
|
|
|
|
|
|
private static final String encodePatternString = "([\\x{10000}-\\x{10ffff}\ud800-\udfff])";
|
|
|
|
|
|
|
|
private static final Pattern encodePattern = Pattern.compile(encodePatternString);
|
|
|
|
|
|
|
|
private static final String decodePatternString = "\\[\\[(.*?)\\]\\]";
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private static final Pattern decodePattern = Pattern.compile(decodePatternString);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
|
|
* @Description 将字符串中的emoji表情转换成可以在utf-8字符集数据库中保存的格式(表情占4个字节,需要utf8mb4字符集)
|
|
|
|
|
|
|
|
* @param str 待转换字符串
|
|
|
|
|
|
|
|
* @return 转换后字符串
|
|
|
|
|
|
|
|
* @throws UnsupportedEncodingException exception
|
|
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
public static String encode(String str) {
|
|
|
|
|
|
|
|
if (null == str) {
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
Matcher matcher = encodePattern.matcher(str);
|
|
|
|
|
|
|
|
StringBuffer sb = new StringBuffer();
|
|
|
|
|
|
|
|
while (matcher.find()) {
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
|
|
|
matcher.appendReplacement(sb, "[[" + URLEncoder.encode(matcher.group(1), "UTF-8") + "]]");
|
|
|
|
|
|
|
|
} catch (UnsupportedEncodingException e) {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
matcher.appendTail(sb);
|
|
|
|
|
|
|
|
return sb.toString();
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
|
|
* @Description 还原utf8数据库中保存的含转换后emoji表情的字符串
|
|
|
|
|
|
|
|
* @param str 转换后的字符串
|
|
|
|
|
|
|
|
* @return 转换前的字符串 exception
|
|
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
public static String decode(String str) {
|
|
|
|
|
|
|
|
if (null == str) {
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
Matcher matcher = decodePattern.matcher(str);
|
|
|
|
|
|
|
|
StringBuffer sb = new StringBuffer();
|
|
|
|
|
|
|
|
while (matcher.find()) {
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
|
|
|
matcher.appendReplacement(sb, URLDecoder.decode(matcher.group(1), "UTF-8"));
|
|
|
|
|
|
|
|
} catch (UnsupportedEncodingException e) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
matcher.appendTail(sb);
|
|
|
|
|
|
|
|
return sb.toString();
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|