package com.carwash.common.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmojiUtil {
/**
*
* ============================================================================
* @Description: TODO(将字符串中的emoji表情转换成可以在utf-8字符集数据库中保存的格式(表情占4个字节,需要utf8mb4字符集))
* @author linchi 1378642054@qq.com
* @date 2019-10-19 19:26:04
* @param @param str
* @param @return 设定文件
* @throws
* ============================================================================
*/
public static String emojiConverStr(String str) {
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) {
e.printStackTrace();
}
}
matcher.appendTail(sb);
System.out.println("emojiConvert " + str + " to " + sb.toString()
+ ", len:" + sb.length());
return sb.toString();
}
/**
*
* ============================================================================
* @Description: TODO(还原utf8数据库中保存的含转换后emoji表情的字符串)
* @author linchi 1378642054@qq.com
* @date 2019-10-19 19:26:14
* @param @param str
* @param @return 设定文件
* @throws
* ============================================================================
*/
public static String StrCoveryEmoji(String str) {
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) {
e.printStackTrace();
}
}
matcher.appendTail(sb);
return sb.toString();
}
}
最后建议大家昵称字段使用utf8mb4类型 因为在mysql中utf8类型并非java中的utf-8对应的类型,有兴趣的朋友可以了解一下,这算是mysql官方不愿提及的一个bug吧