The utf16 count is correct, not the utf8 count. Or, best, use the convenience initializers, which convert a Range
of String.Index
to a NSRange
:
let range = NSRange(str.startIndex..., in: str)
And to convert NSRange
to String.Range
:
let range = Range(nsRange, in: str)
Thus, putting that together:
let str = "#tweak #wow #gaming"
if let regex = try? NSRegularExpression(pattern: "#[a-z0-9]+", options: .caseInsensitive) {
let nsRange = NSRange(str.startIndex..., in: str)
let strings = regex.matches(in: str, range: nsRange).compactMap {
Range($0.range, in: str).map { str[$0] }
}
print(strings)
}
See WWDC 2017 Efficient Interactions with Frameworks, which talks about (a) our historical use of UTF16 when dealing with ranges; and (b) the fact that we don’t have to do that any more.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…