原创

Java过滤Emoji表情插入不到数据库问题

现在输入法都带有表情输入,特别是QQ或者微信昵称带的特殊字符就更多了,这些数据在插入数据库的时候会报如下错误
file
根据业务的需要,我这里直接将emoji表情处理掉,改变成*代替,为什么插入不进去呢,具体的原因是
UTF-8编码有可能是2个3个或者是4个字节。而Emoji表情是4个字节,Mysql的utf8编码最多3个字节,所以数据插不进去。网上说将数据库的格式设置成Utf-8mb4,这个方法没测试过,因此这里不讨论这种方案。以下是我的工具类,直接粘贴使用即可。


import com.alibaba.druid.util.StringUtils;

/**
 * @Author: haohaowang
 * @Desc
 * @Date: 2019/4/22 16:47
 */
public class EmojiFilter {
    /**
     * 检测是否有emoji字符
     *
     * @param source
     * @return 一旦含有就抛出
     */
    public static boolean containsEmoji(String source) {
        if (StringUtils.isEmpty(source)) {
            return false;
        }
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (isEmojiCharacter(codePoint)) {
                //do nothing,判断到了这里表明,确认有表情字符
                return true;
            }
        }
        return false;
    }

    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }

    /**
     * 过滤emoji 或者 其他非文字类型的字符
     *
     * @param source
     * @return
     */
    public static String filterEmoji(String source) {
        System.out.println("过滤特殊字符:"+source);
        source = source.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "*");
        if (!containsEmoji(source)) {
            return source;//如果不包含,直接返回
        }
        //到这里铁定包含
        StringBuilder buf = null;
        int len = source.length();

        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);

            if (isEmojiCharacter(codePoint)) {
                if (buf == null) {
                    buf = new StringBuilder(source.length());
                }

                buf.append(codePoint);
            } else {
                buf.append("*");
            }
        }

        if (buf == null) {
            return source;//如果没有找到 emoji表情,则返回源字符串
        } else {
            if (buf.length() == len) {//这里的意义在于尽可能少的toString,因为会重新生成字符串
                buf = null;
                return source;
            } else {
                return buf.toString();
            }
        }

    }
//调用过滤
    public static void main(String[] args) {
        String s = filterEmoji("");
        System.out.println(s);
    }
}

如果小伙伴又别的方法,经过自己测试过的,可以在下面留言。进行补充

正文到此结束(点击广告是对作者最大的支持)