[英]What is the correct length: argument to provide to NSRange for NSRegularExpression using a (Swift) String?
I'm confused on how to use the NSRegularExpression
class in Swift, especially the :length
parameter of NSRange
.我对如何在 Swift 中使用
NSRegularExpression
类感到困惑,尤其是NSRange
的:length
参数。
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
:一些教程说NSRegularExpression只应适用于NSString的情况下,也有人说这是确定的将其应用到(SWIFT)的字符串情况下,只要你提供
utf8.count
或utf16.count
到:length
的参数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.
由于 Swift 和 Objective-C 中处理字符串的方式不同,您需要为 NSRange 实例提供来自 NSString 而不是来自 String 的字符串长度。
This is, roughly speaking, because NSString uses fixed-width encoding and String uses variable-width encoding.
粗略地说,这是因为 NSString 使用固定宽度编码,而 String 使用可变宽度编码。
Furthermore, is the following documentation really the best Apple can do with respect to documenting the NSRegularExpression
class in Swift?此外,就在 Swift 中记录
NSRegularExpression
类而言,以下文档真的是 Apple 所能做的最好的吗?
https://developer.apple.com/documentation/foundation/nsregularexpression 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?
有没有更详细的文档?
The utf16 count is correct, not the utf8 count. utf16 计数是正确的,而不是 utf8 计数。 Or, best, use the convenience initializers, which convert a
Range
of String.Index
to a NSRange
:或者,最好使用便利初始化程序,它将
String.Index
的Range
转换为NSRange
:
let range = NSRange(str.startIndex..., in: str)
And to convert NSRange
to String.Range
:并将
NSRange
转换为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 2017Efficient Interactions with Frameworks , which talks about (a) our historical use of UTF16 when dealing with ranges;参见 WWDC 2017Efficient Interactions with Frameworks ,其中讨论了 (a) 我们在处理范围时使用 UTF16 的历史; and (b) the fact that we don't have to do that any more.
(b) 我们不必再这样做了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.