我使用以下扩展方法来获取子字符串的NSRange数组:
extension String {
func nsRangesOfString(findStr:String) -> [NSRange] {
let ranges: [NSRange]
do {
// Create the regular expression.
let regex = try NSRegularExpression(pattern: findStr, options: [])
// Use the regular expression to get an array of NSTextCheckingResult.
// Use map to extract the range from each result.
ranges = regex.matches(in: self, options: [], range: NSMakeRange(0, self.characters.count)).map {$0.range}
}
catch {
// There was a problem creating the regular expression
ranges = []
}
return ranges
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我没有意识到为什么它有时不起作用.这是两个类似的案例,一个是作品而另一个不是:
那个工作:
自(字符串):
"וצפן(קרי:יִצְפֹּ֣ן)לַ֭יְשָׁרִיםתּוּשִׁיָּ֑המָ֝גֵ֗ןלְהֹ֣לְכֵיתֹֽם:"
FINDSTR:
"קרי:"
而那个不是:
自(字符串):
"לִ֭נְצֹראָרְח֣וֹתמִשְׁפָּ֑טוְדֶ֖רֶךְחסידו(קרי:חֲסִידָ֣יו)יִשְׁמֹֽר:"
FINDSTR:
"קרי:"
(另一种稳定的方法虽然是合适的答案.)
NSRange范围是以UTF-16代码单位(NSString内部使用的)为单位指定的,因此长度必须为
self.utf16.count:
ranges = regex.matches(in: self, options: [],
range: NSRange(location: 0, length: self.utf16.count))
.map {$0.range}
Run Code Online (Sandbox Code Playgroud)
在我们的第二个字符串的情况下
let s2 = "???????? ????????? ?????????? ????????? ????? (???: ??????????) ??????????"
print(s2.characters.count) // 46
print(s2.utf16.count) // 74
Run Code Online (Sandbox Code Playgroud)
这就是为什么你的代码找不到模式的原因.
从Swift 4开始,您也可以NSRange为整个字符串计算a
NSRange(self.startIndex..., in: self)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
351 次 |
| 最近记录: |