再項(xiàng)目中遇到了emoji存儲的問題,苦于后臺已經(jīng)有不少數(shù)據(jù),想要置換說是難度很大漾脂,所以存儲的問題落到了前端身上。
查了一些資料胚鸯,網(wǎng)上比較普遍的做法還是數(shù)據(jù)庫升級惑朦,但是也有不少資料可供參考伙菊,其中用到的思想就是正則表達(dá)式和講emoji轉(zhuǎn)化為對應(yīng)十六進(jìn)制對應(yīng)的字符串沉桌。這里轉(zhuǎn)化16進(jìn)制是utf-8編碼的十六進(jìn)制編碼领迈,主要是為了配合ios端。使用這種方法傲须,可以將emoji變?yōu)閿?shù)據(jù)庫可以存儲的字符串蓝牲。本來做了就做了,后來同事將網(wǎng)上沒有看到類似的方法泰讽,所以想到還是放到網(wǎng)上來吧例衍。源碼放下邊
···
public class EmojiUtils {
public static final Stringpatch ="[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]";
? ? public static final Stringpatch2 ="\\[+[0-9a-fA-F]+]";
? ? /**
* 將含有4字節(jié)字符的字符轉(zhuǎn)為固定格式
*
? ? * @param msg
? ? * @return
? ? */
? ? public static StringgetEmoji(String msg) {
LogUtil.showTime(msg +"emoji2");
? ? ? ? Pattern pattern = Pattern.compile(patch);
? ? ? ? Matcher matcher = pattern.matcher(msg);
? ? ? ? StringBuffer sb =new StringBuffer();
? ? ? ? try {
while (matcher.find()) {
byte[] count;
? ? ? ? ? ? ? ? count = URLDecoder.decode(matcher.group(), "UTF-8").getBytes();
? ? ? ? ? ? ? ? String cha ="[";
? ? ? ? ? ? ? ? for (int i =0; i < count.length; i++) {
String s = Integer.toHexString(count[i]);
? ? ? ? ? ? ? ? ? ? if (s.length() >2) {
s = s.substring(s.length() -2);
? ? ? ? ? ? ? ? ? ? }
cha += s;
? ? ? ? ? ? ? ? }
cha +="]";
? ? ? ? ? ? ? ? matcher.appendReplacement(sb, cha);
? ? ? ? ? ? }
}catch (Exception e) {
e.printStackTrace();
? ? ? ? }
matcher.appendTail(sb);
? ? ? ? LogUtil.showTime(msg +"emoji2");
? ? ? ? return sb.toString();
? ? }
/**
* 將含有固定格式的字符串轉(zhuǎn)化為四字節(jié)字符
*
? ? * @param msg
? ? * @return
? ? */
? ? public static StringgetString(String msg) {
LogUtil.showTime(msg +"emoji");
? ? ? ? Pattern pattern = Pattern.compile(patch2);
? ? ? ? Matcher matcher = pattern.matcher(msg);
? ? ? ? StringBuffer sb =new StringBuffer();
? ? ? ? while (matcher.find()) {
String count = matcher.group();
//? ? ? ? ? ? LogUtil.show("轉(zhuǎn)換之前的十六進(jìn)制" + count);
? ? ? ? ? ? count = count.substring(1, count.length() -1);
? ? ? ? ? ? matcher.appendReplacement(sb, hexStringToString(count));
? ? ? ? }
matcher.appendTail(sb);
? ? ? ? LogUtil.showTime(msg +"emoji");
? ? ? ? return sb.toString();
? ? }
/**
* 16進(jìn)制字符串轉(zhuǎn)換為字符串
*
? ? * @param s
? ? * @return
? ? */
? ? public static StringhexStringToString(String s) {
if (s ==null || s.equals("")) {
return null;
? ? ? ? }
s = s.replace(" ", "");
? ? ? ? byte[] baKeyword =new byte[s.length() /2];
? ? ? ? for (int i =0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (Integer.parseInt(
s.substring(i *2, i *2 +2), 16));
? ? ? ? ? ? }catch (Exception e) {
e.printStackTrace();
? ? ? ? ? ? }
}
try {
s =new String(baKeyword, "UTF-8");
? ? ? ? }catch (Exception e1) {
e1.printStackTrace();
? ? ? ? }
return s;
? ? }
}
···