How to extract emojis from a string?

前端 未结 1 1832
粉色の甜心
粉色の甜心 2021-01-07 04:27

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 cha

相关标签:
1条回答
  • 2021-01-07 04:46

    The Set of Emoji characters

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

    Disclaimer

    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.

    Extending Character

    Now we need a way to calculate the Unicode Scalar Code Point of a Character. For this I am using the solution provided here.

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

    Extending String

    This extension does allow you to extract the emoji characters from a String.

    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

    let sentence = "                                                                    
    0 讨论(0)
提交回复
热议问题