Extract emoji (unicode) from NSString [duplicate]

2019-07-11 19:39发布

This question already has an answer here:

I have to parse some strings and extract emojis.

I can't found any good solution to do it.

Let say that i have this string:

" xxx

1条回答
姐就是有狂的资本
2楼-- · 2019-07-11 20:05

This code works only in the latest iOS 10 SDK, and cannot detect some combined emojis, but if that's OK with you, please try:

func emojis(_ str: String) -> [String]  {
    //You may need to add some extra characters as "Umbrella on ground" does not have property "Emoji_Presentation".
    let emojiPattern1 = "[\\p{Emoji_Presentation}\\u26F1]" //Code Points with default emoji representation
    let emojiPattern2 = "\\p{Emoji}\\uFE0F" //Characters with emoji variation selector
    let emojiPattern3 = "\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}" //Characters with emoji modifier
    let emojiPattern4 = "[\\U0001F1E6-\\U0001F1FF][\\U0001F1E6-\\U0001F1FF]" //2-letter flags
    let pattern = "\(emojiPattern4)|\(emojiPattern3)|\(emojiPattern2)|\(emojiPattern1)"
    let regex = try! NSRegularExpression(pattern: pattern, options: [])
    let matches = regex.matches(in: str, options: [], range: NSRange(0..<str.utf16.count))
    return matches.map{(str as NSString).substring(with: $0.range)}
}

print(emojis(" xxx                                                                     
查看更多
登录 后发表回答