0
点赞
收藏
分享

微信扫一扫

java实现表情过滤

weipeng2k 2022-01-17 阅读 40
/**
     * @Description: 过滤表情
     */
    private final static int NAME_LEN_MIN = 2;
    private final static int NAME_LEN_MAX = 18;
    private final static int MAX_THREE_UTF8 = 0xF0;
    private final static int BYTE_MASK = 0xFF;
    private final static byte[] DEFAULT_REPLACE = "".getBytes();
    private final static int FOLLOW_BYTE_MIN = 0x80;
    //private final static int FOLLOW_BYTE_MAX = 0xB0;
    private final static int FOLLOW_BYTE_MAX = 0xBF;

    public static String filterUTF8OutThree(String vStr, String replace) {
        if (StringUtils.isBlank(vStr)) {
            return ".";
        }
        byte[] tStrBytes = vStr.getBytes();
        List<Byte> tResultList = new ArrayList<>();
        byte[] replaceByte = replace == null ? DEFAULT_REPLACE : replace.getBytes();

        boolean tRemoveSign = false;
        for (byte tStrByte : tStrBytes) {
            int tTmpByte = tStrByte & BYTE_MASK;
            if (MAX_THREE_UTF8 <= tTmpByte) {
                tRemoveSign = true;
                //符号替换
                for (byte tChangeByte : replaceByte) {
                    tResultList.add(tChangeByte);
                }
                //第二位及以后字符
            } else if (FOLLOW_BYTE_MIN <= tTmpByte && FOLLOW_BYTE_MAX >= tTmpByte) {
                if (false == tRemoveSign)
                    tResultList.add(tStrByte);
            } else {
                tRemoveSign = false;
                tResultList.add(tStrByte);
            }
        }
        byte[] tResultBytes = new byte[tResultList.size()];
        for (int i = 0; i < tResultList.size(); i++) {
            tResultBytes[i] = tResultList.get(i);
        }
        try {
            return new String(tResultBytes, "utf-8");
        } catch (UnsupportedEncodingException e) {
            log.warn("字符串转utf-8失败!!! str={}", vStr, e);
            return vStr;
        }
    }
举报

相关推荐

0 条评论