Swift - Replacing emojis in a string with whitespace

前端 未结 6 1408
悲&欢浪女
悲&欢浪女 2020-12-18 11:05

I have a method that detects urls in a string and returns me both the urls and the ranges where they can be found. Everything works perfectly until there are emojis on the s

6条回答
  •  感情败类
    2020-12-18 11:23

    You can use pattern matching (for emoji patterns) to filter out emoji characters from your String.

    extension String {
    
        var emojilessStringWithSubstitution: String {
            let emojiPatterns = [UnicodeScalar(0x1F601)...UnicodeScalar(0x1F64F),
                                 UnicodeScalar(0x2702)...UnicodeScalar(0x27B0)]
            return self.unicodeScalars
                .filter { ucScalar in !(emojiPatterns.contains{ $0 ~= ucScalar }) }
                .reduce("") { $0 + String($1) }
        }  
    }
    
    /* example usage */
    let str = "I'm gonna do this callenge as soon as I can swing again 

提交回复
热议问题