1. 程式人生 > >JAVA實現過濾掉文字中的表情

JAVA實現過濾掉文字中的表情

公司是做電商的,在資料採集這方面,要進行大量的資料採集,在資料採集的時候遇到了很多的問題,有一些文字包含表情,資料庫用的是utf8字符集,這樣就儲存到資料庫中就會報錯,本來是可以把資料庫的字符集改成utf8mb4,這樣就可以儲存帶有表情,,但是考慮一直在使用utf8,則就使用了過濾掉文字中的表情;程式碼如下: package com.zjr.common.utils;

import org.apache.commons.lang3.StringUtils;

public class EmojiFilter {

/**
 * 檢測是否有emoji字元
 * 
 * @param source
 * @return 一旦含有就丟擲
 */
public static boolean containsEmoji(String source) {
    if (StringUtils.isBlank(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) {

    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);
        } 
    }

    if (buf == null) {
        return source;// 如果沒有找到 emoji表情,則返回源字串
    } else {
        if (buf.length() == len) {// 這裡的意義在於儘可能少的toString,因為會重新生成字串
            buf = null;
            return source;
        } else {
            return buf.toString();
        }
    }
}

}