Emoji表情处理工具类

Posted kesimin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Emoji表情处理工具类相关的知识,希望对你有一定的参考价值。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmojiToString {
    /**
     * 将str中的emoji表情转为byte数组
     *
     * @param str
     * @return
     */
    public static String resolveToByteFromEmoji(String str) {
        if(str != null && str != ""){
            Pattern pattern = Pattern
                    .compile("[^(u2E80-u9FFF\w\s`[email protected]#\$%\^&\*\(\)_+-?()——=\[\]{}\|;。,、《》”:;“!……’:‘"<,>\.?/\\*)]");
            Matcher matcher = pattern.matcher(str);
            StringBuffer sb2 = new StringBuffer();
            while (matcher.find()) {
                matcher.appendReplacement(sb2, resolveToByte(matcher.group(0)));
            }
            matcher.appendTail(sb2);
            return sb2.toString();
        }
        return str;
    }

    /**
     * 将str中的byte数组类型的emoji表情转为正常显示的emoji表情
     *
     * @param str
     * @return
     */
    public static String resolveToEmojiFromByte(String str) {
        if(str != null && str != ""){
            Pattern pattern2 = Pattern.compile("<:([[-]\d*[,]]+):>");
            Matcher matcher2 = pattern2.matcher(str);
            StringBuffer sb3 = new StringBuffer();
            while (matcher2.find()) {
                matcher2.appendReplacement(sb3, resolveToEmoji(matcher2.group(0)));
            }
            matcher2.appendTail(sb3);
            return sb3.toString();
        }
        return str;
    }

    private static String resolveToByte(String str) {
        byte[] b = str.getBytes();
        StringBuffer sb = new StringBuffer();
        sb.append("<:");
        for (int i = 0; i < b.length; i++) {
            if (i < b.length - 1) {
                sb.append(Byte.valueOf(b[i]).toString() + ",");
            } else {
                sb.append(Byte.valueOf(b[i]).toString());
            }
        }
        sb.append(":>");
        return sb.toString();
    }

    private static String resolveToEmoji(String str) {
        str = str.replaceAll("<:", "").replaceAll(":>", "");
        String[] s = str.split(",");
        byte[] b = new byte[s.length];
        for (int i = 0; i < s.length; i++) {
            b[i] = Byte.valueOf(s[i]);
        }
        return new String(b);
    }

}

 

以上是关于Emoji表情处理工具类的主要内容,如果未能解决你的问题,请参考以下文章

Python string中删除(过滤)掉emoji表情字符

安卓怎么处理emoji表情提交给后台

emoji表情处理,emoji表情的编码解码

emoji表情鲸鱼的代码

python 怎么过滤 emoji 表情符号

MYSQL 写入emoji表情字符处理