mysql中emoji表情转换入库,超级实用

emoji表情符在平时用的时候特别的爽,但是有时候在开发的时候就比较的难受,微信开发昵称往往都有表情符导致无法入库。尝试了往上很多的方法都没有得以解决,甚至我改了数据库配置后发现库不能启动了(哎哟我靠,感谢那些博主的建议)。所以今天给大家个工具类,用着是挺舒服的。

public class EmojiUtil {
	/**
	 * @Description emoji表情转换入库
	 * @param str 待转换字符串
	 * @return 转换后字符串
	 * @throws UnsupportedEncodingException
	 */
	public static String emojiToUtf(String str)
	        throws UnsupportedEncodingException {
	    String patternString = "([\\x{10000}-\\x{10ffff}\ud800-\udfff])";
	    Pattern pattern = Pattern.compile(patternString);
	    Matcher matcher = pattern.matcher(str);
	    StringBuffer con = new StringBuffer();
	    while (matcher.find()) {
	        try {
	            matcher.appendReplacement(con,"[[" + URLEncoder.encode(matcher.group(1),"UTF-8") + "]]");
	        } catch (UnsupportedEncodingException e) {
	            throw e;
	        }
	    }
	    matcher.appendTail(con);
	    return con.toString();
	}

	/**
	 * @Description 还原emoji表情的字符串
	 * @param str 转换后的字符串
	 * @return 转换前的字符串
	 * @throws UnsupportedEncodingException
	 */
	public static String utfToEmoji(String str)
	        throws UnsupportedEncodingException {
	    String patternString = "\\[\\[(.*?)\\]\\]";

	    Pattern pattern = Pattern.compile(patternString);
	    Matcher matcher = pattern.matcher(str);

	    StringBuffer con = new StringBuffer();
	    while (matcher.find()) {
	        try {
	            matcher.appendReplacement(con,
	                    URLDecoder.decode(matcher.group(1), "UTF-8"));
	        } catch (UnsupportedEncodingException e) {
	            throw e;
	        }
	    }
	    matcher.appendTail(con);
	    return con.toString();
	}

第一个方法是将字段中的emoji表情转换入库。

String content=“”;
try {
			content = EmojiUtil.emojiToUtf(content);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

转换后入库。

第二个方法是讲 转化后的字符还原为 emoji表情:

String content = comm.getStr("content");
			if (StringUtils.isNotBlank(content)) {
				try {
					content = EmojiUtil.utfToEmoji(content);
					comm.set("content", content);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}

嗯,大概就是這個样子。

给大家推荐一个公众号里面有很多的学习资料、视频挺不错的。
在这里插入图片描述

  • 10
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值