packageutils;importjava.io.UnsupportedEncodingException;importjava.net.URLDecoder;importjava.net.URLEncoder;importjava.util.regex.Matcher;importjava.util.regex.Pattern;importorg.apache.commons.lang.StringUtils;public classEmojiUtils {/*** emoji表情替换
*
*@paramsource 原字符串
*
*@paramslipStr emoji表情替换成的字符串
*
*@return过滤后的字符串*/
public staticString filterEmoji(String source, String slipStr) {if(StringUtils.isNotBlank(source)) {return source.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", slipStr);
}else{returnsource;
}
}/*** @Description 将字符串中的emoji表情转换成可以在utf-8字符集数据库中保存的格式(表情占4个字节,需要utf8mb4字符集)
*@paramstr
* 待转换字符串
*@return转换后字符串
*@throwsUnsupportedEncodingException
* exception*/
public static String emojiConvert(String str) throwsUnsupportedEncodingException {
String patternString= "([\\x{10000}-\\x{10ffff}\ud800-\udfff])";
Pattern pattern=Pattern.compile(patternString);
Matcher matcher=pattern.matcher(str);
StringBuffer sb= newStringBuffer();while(matcher.find()) {try{
matcher.appendReplacement(sb,"[[" + URLEncoder.encode(matcher.group(1), "UTF-8") + "]]");
}catch(UnsupportedEncodingException e) {throwe;
}
}
matcher.appendTail(sb);returnsb.toString();
}/*** @Description 还原utf8数据库中保存的含转换后emoji表情的字符串
*@paramstr
* 转换后的字符串
*@return转换前的字符串
*@throwsUnsupportedEncodingException
* exception*/
public static String emojiRecovery2(String str) throwsUnsupportedEncodingException {
String patternString= "\\[\\[(.*?)\\]\\]";
Pattern pattern=Pattern.compile(patternString);
Matcher matcher=pattern.matcher(str);
StringBuffer sb= newStringBuffer();while(matcher.find()) {try{
matcher.appendReplacement(sb, URLDecoder.decode(matcher.group(1), "UTF-8"));
}catch(UnsupportedEncodingException e) {throwe;
}
}
matcher.appendTail(sb);returnsb.toString();
}
}