Similarly as in Swift extract regex matches,
you have to pass an NSRange
to the match functions, and the
returned ranges are NSRange
s as well. This can be achieved
by converting the given text to an NSString
.
The #S+
pattern matches a #
followed by one or more
non-whitespace characters.
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))
}
Output:
(15,10)
#hashtag??
(62,10)
#hashtag??
You can also convert between NSRange
and Range<String.Index>
using the methods from NSRange to Range<String.Index>.
Remark: As @WiktorStribi?ew correctly noticed, the above pattern
will include trailing punctuation (commas, periods, etc). If
that is not desired then
let regex = try NSRegularExpression(pattern: "#[^[:punct:][:space:]]+", options: [])
would be an alternative.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…