在 Swift 中从字符串中删除表情符号

Dan*_*iel 1 swift

如何使用以下扩展从字符串中过滤表情符号?

extension String {
    func removeCharacters() -> String {
        let removeCharacters: CharacterSet = [" ", ";", ",", ":", ".", "!", "%", "$", "&", "#", "*", "^", "@", "(", ")", "/"]
        let filteredString = self.unicodeScalars.filter { !removeCharacters.contains($0) }
        return String(String.UnicodeScalarView(filteredString))
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道isEmojiPresentation == false可以使用属性,只是不确定如何将其添加到函数中。为了澄清,所有表情符号都应该从通过扩展传递的字符串中删除。

amb*_*ded 5

我编写了这个 Swift 5 扩展来删除表情符号字符:

\n
extension String {\n    func withoutEmoji() -> String {\n        filter { $0.isASCII }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

您可以运行此单元测试来查看它是否有效:

\n
func test_removingEmoji_shouldReturnStringWithoutEmoji() {\n        // Given\n        let inputText = "Hell\xe2\x98\xba\xef\xb8\x8f\xe2\x80\x8d\xe2\x80\x8d\xe2\x80\x8do World\xe2\x9d\xa4\xef\xb8\x8f"\n        \n        // When\n        let emojilessText = inputText.withoutEmoji()\n        \n        // Then\n        let expectedString = "Hello World"\n        XCTAssertEqual(emojilessText, expectedString, "\\(String(describing: asData(emojilessText))) should be equal to \\(String(describing: asData(expectedString)))")\n    }\n    \n// Helper function that returns the string as Data. \n// Reveals any invisible characters that might have remained in the string. \n// This can help you to understand why two strings might not be considered equal, even if they look the same.\nprivate func asData(_ text: String) -> NSData? {\n    text.data(using: .utf8) as? NSData\n}\n
Run Code Online (Sandbox Code Playgroud)\n

限制:正如“hotdougsoup.nl”在评论中指出的那样,这也会删除国际字符。

\n
\n

替代解决方案

\n

通过建立在 Leo Dabus 伟大的答案的基础上,我写了这个小扩展,将表情符号字符排除在可见的眼睛之外。然而,单元测试显示仍然存在一些看不见的字符。这就是为什么我决定使用上面较短的代码片段 (.isASCII)。

\n
// This does not remove all characters reliably. Use the solution above.\nextension String {\n    func withoutEmoji() -> String {\n        unicodeScalars\n            .filter { (!$0.properties.isEmojiPresentation && !$0.properties.isEmoji) || $0.properties.numericType == .decimal }\n            .reduce(into: "") { $0 += String($1) }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

  • 请注意,`.isASCII` 还会删除国际字符,例如:éëüñß (4认同)