小表情转化为字符串存储到mysql数据库,还原字符串为小表情

近期做一个项目,实际生产环境中,在测试代码的时候,发现有些员工的昵称是小表情(小猪)。
将小猪获取转化为字符串格式。
废话少说,见代码:

//转换小表情为字符串
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) {
            System.out.println(e);
            throw e;
        }
    }
    matcher.appendTail(sb);
    System.out.println("emojiConvert " + str + " to " + sb.toString()
            + ", len:" + sb.length());
    System.out.println("**********************************************"+sb.toString());
    return sb.toString();
}

//还原字符串为小表情
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) {
            System.out.println(e);
            throw e;
        }
    }
    matcher.appendTail(sb);
    System.out.println("emojiRecovery " + str + " to " + sb.toString());
    return sb.toString();
}

}

猜你喜欢

转载自blog.csdn.net/weixin_43806056/article/details/92803778