我试图找到一个字符串的特定子串的范围.每个子字符串都以一个标签开头,并且可以包含任何它喜欢的字符(包括表情符号).应在不同范围检测重复的主题标签.一位来自此处的用户建议使用以下代码:
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)")
}
Run Code Online (Sandbox Code Playgroud)
但是,此代码不适用于emojis.包含表情符号的正则表达式是什么?有没有办法检测a #,后跟任何字符,直到空格/换行符?
Mar*_*n R 12
与Swift提取正则表达式匹配类似,您必须传递NSRange给匹配函数,返回的范围也是NSRanges.这可以通过将给定文本转换为NSString.
该#\S+模式匹配a #后跟一个或多个非空白字符.
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))
}
Run Code Online (Sandbox Code Playgroud)
输出:
(15,10) #hashtag (62,10) #hashtag
您还可以在NSRange和Range <String.Index>之间转换NSRange和Range<String.Index>
使用方法.
备注:正如@WiktorStribiżew正确注意到的,上述模式将包括尾随标点符号(逗号,句号等).如果那不是那么的话
let regex = try NSRegularExpression(pattern: "#[^[:punct:][:space:]]+", options: [])
Run Code Online (Sandbox Code Playgroud)
将是一个替代方案.