美文网首页
NSRegularExpression 正则匹配带有表情emoj

NSRegularExpression 正则匹配带有表情emoj

作者: angryAnt的简书 | 来源:发表于2019-03-07 18:03 被阅读0次

当用NSRegularExpression去正则匹配带有表情emoji的字符串的时候,会出现匹配不全的情况

例:

let string = "😳😳😳😳😳😳 [gggg] [gggg] [gggg] [gggg]"
let pattern = "\\[.*?\\]"
if let regularExpression = try? NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.dotMatchesLineSeparators) {
   var matches = regularExpression.matches(in: text, options: NSRegularExpression.MatchingOptions.withTransparentBounds, range: NSRange(location: 0, length: string.count))
   print(matches)
}

只会打印出


image.png

明显是emoji的锅,只要我们改一下range的length就行

let range = NSRange(location: 0, length: string.utf16.count)

就可以正确打印出:


image.png

END

相关文章

网友评论

      本文标题:NSRegularExpression 正则匹配带有表情emoj

      本文链接:https://www.haomeiwen.com/subject/hldhpqtx.html