I'm confused on how to use the NSRegularExpression
class in Swift, especially the :length
parameter of NSRange
.
Some tutorials say that NSRegularExpression should only be applied to NSString instances, while others say it's OK to apply it to (Swift) string instances as long as you provide utf8.count
or utf16.count
to :length
parameter of NSRange
:
var str : String = "#tweak #wow #gaming"
if let regex = try? NSRegularExpression(pattern: "#[a-z0-9]+", options: .caseInsensitive) {
regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.utf8.count)).map {
print(str.substring(with: $0.range))
}
}
The following are quotes from this source:
Due to the way strings are handled differently in Swift and Objective-C, you will need to provide the NSRange instance with a string length from NSString, and not from String.
This is, roughly speaking, because NSString uses fixed-width encoding and String uses variable-width encoding.
Furthermore, is the following documentation really the best Apple can do with respect to documenting the NSRegularExpression
class in Swift?
https://developer.apple.com/documentation/foundation/nsregularexpression
I'd at least expect a list of properties and methods of the class, but it only show some examples. Is there any more elaborate documentation?