Java中如何检测字符串是否包含emoji?

问题描述 投票:0回答:2

我想用Java检测一个字符串是否包含表情符号。

我尝试过 https://github.com/vdurmont/emoji-java 但它不再维护并且在新表情符号上失败。

例如 - 以下测试失败:

EmojiManager.containsEmoji("This string contains beans 🫘") shouldBe true
java emoji
2个回答
2
投票

在 Java 21 中,您将能够使用

Character#isEmoji(int)
来帮助您。


1
投票

这是更新的答案,包括您在评论中提供的资源。

它应该能够模仿 containsEmoji 方法,尽管它尚未经过充分测试。

我使用了以下资源,Unicode,附件 A – 表情符号属性和数据文件
具体来说,是 emoji-data.txt 数据文件。

我使用以下正则表达式来捕获值。

^([\dA-F]{4,5})(?:\.\.([\dA-F]{4,5}))?

并且,用于编译源代码的打印值。

list.add(new int[] { 0x$1, 0x$2 });\n

将会有几个空的 $2 组,因此您需要使用 查找并替换

我无法粘贴所有代码,因为它超过 30,000 个字符。

public class EmojiUtil {
    static List<int[]> list = new ArrayList<>();

    static {
        /* https://unicode.org/Public/15.0.0/ucd/emoji/emoji-data.txt */
        list.add(new int[] { 0x0023 });
        list.add(new int[] { 0x002a });
        list.add(new int[] { 0x0030, 0x0039 });
        list.add(new int[] { 0x00a9 });
        list.add(new int[] { 0x00ae });
        list.add(new int[] { 0x203c });
        list.add(new int[] { 0x2049 });
        list.add(new int[] { 0x2122 });
        list.add(new int[] { 0x2139 });
        list.add(new int[] { 0x2194, 0x2199 });
        list.add(new int[] { 0x21a9, 0x21aa });
        list.add(new int[] { 0x231a, 0x231b });
        list.add(new int[] { 0x2328 });
        list.add(new int[] { 0x23cf });
        list.add(new int[] { 0x23e9, 0x23ec });
        list.add(new int[] { 0x23ed, 0x23ee });
        /* ... */
    }

    static boolean contains(String string) {
        char[] characters = string.toCharArray();
        char high, low;
        int index, limit;
        for (int[] values : list) {
            if (values.length == 1) limit = values[0];
            else limit = values[1];
            for (int codePoint = values[0]; codePoint <= limit; codePoint++) {
                if (codePoint > 0xffff) {
                    high = Character.highSurrogate(codePoint);
                    low = Character.lowSurrogate(codePoint);
                    if ((index = Arrays.binarySearch(characters, (char) high)) >= 0) {
                        if (index + 1 < characters.length && characters[index + 1] == (char) low)
                            return true;
                    }
                } else if (Arrays.binarySearch(characters, (char) values[0]) >= 0)
                    return true;
            }
        }
        return false;
    }
}

示例

EmojiUtil.contains("This string contains beans \uD83E\uDED8");
© www.soinside.com 2019 - 2024. All rights reserved.