如何从字符串中提取表情符号? [英] How to extract emojis from a string?

查看:435
本文介绍了如何从字符串中提取表情符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来获取 String 并提取表情符号字符。
我知道Emojis是Unicode的一部分,所以我需要删除某些Unicode字符子集。我真的不知道从哪里开始。

I'm looking for a way to take a String and extract Emoji characters. I know that Emojis are part of Unicode so I need to remove a certain subset of Unicode characters. I don't really know where to start.

推荐答案

表情符号集



首先,我们需要一个 Set ,其中包含代表表情符号的unicode值。

The Set of Emoji characters

First of all we need a Set containing the unicode values representing the emoji.


免责声明

对于这个答案,我使用的是表情系列(1F601-1F64F)和标志(2702-27B0)向您展示解决方案。但请注意,您应根据需要添加其他范围

For this answer I am using the range of Emoticons (1F601-1F64F) and Dingbats (2702-27B0) to show you the solution. However keep in mind that you should add further ranges depending on your needs.



扩展字符



现在我们需要一种方法来计算Unicode标量码点一个人物。为此我使用这里提供的解决方案

extension Character {
    private var unicodeScalarCodePoint: Int {
        let characterString = String(self)
        let scalars = characterString.unicodeScalars
        return Int(scalars[scalars.startIndex].value)
    }
}



扩展字符串



此扩展程序允许您从<$ c $中提取表情符号字符c>字符串。

extension String {
    var emojis:[Character] {
        let emojiRanges = [0x1F601...0x1F64F, 0x2702...0x27B0]
        let emojiSet = Set(emojiRanges.flatten())
        return self.characters.filter { emojiSet.contains($0.unicodeScalarCodePoint) }
    }
}



测试



Testing

这篇关于如何从字符串中提取表情符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆