使用正则表达式匹配表情符号以及字符串中的文本

时间:2016-09-26 11:12:47

标签: ios regex swift

我试图找到一个字符串的特定子串的范围。每个子字符串都以一个标签开头,并且可以包含任何它喜欢的字符(包括表情符号)。应在不同范围检测重复的主题标签。一位来自此处的用户建议使用此代码:

var str = "The range of #hashtag should be different to this #hashtag"
let regex = try NSRegularExpression(pattern: "(#[A-Za-z0-9]*)", options: [])
let matches = regex.matchesInString(str, options:[], range:NSMakeRange(0, str.characters.count))
for match in matches {
    print("match = \(match.range)")
}

但是,此代码不适用于emojis。包含表情符号的正则表达式是什么?有没有办法检测#,后跟任何字符,直到空格/换行符?

1 个答案:

答案 0 :(得分:11)

Swift extract regex matches类似, 你必须将NSRange传递给匹配函数,并且 返回的范围也是NSRange。这可以实现 将给定文本转换为NSString

#\S+模式匹配#后跟一个或多个 非空白字符。

let text = "The range of #hashtag should  be  different to this #hashtag"

let nsText = text as NSString
let regex = try NSRegularExpression(pattern: "#\\S+", options: [])
for match in regex.matchesInString(text, options: [], range: NSRange(location: 0, length: nsText.length)) {
    print(match.range)
    print(nsText.substringWithRange(match.range))
}

输出:

(15,10)
#hashtag
(62,10)
#hashtag

您还可以在NSRangeRange<String.Index>之间进行转换 使用NSRange to Range<String.Index>中的方法。

备注:正如@WiktorStribiżew正确注意到的,上面的模式 将包括尾随标点符号(逗号,句号等)。如果 那是不希望的

let regex = try NSRegularExpression(pattern: "#[^[:punct:][:space:]]+", options: [])

将是另一种选择。