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();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM