更新 Swift 中的范围 3

Update a Range in Swift 3

我正在尝试使用以下代码段(它在 String 的扩展中)搜索 String for regex

var range = self.startIndex..<self.endIndex

while range.lowerBound < range.upperBound {
    if let match = self.range(of: regex, options: .regularExpression, range: range, locale: nil) {

        print(match)
        range = ????? <============  this line, how do I update the range?
    }
}

它会正确找到第一次出现,但我不知道如何将范围更改为匹配的位置以搜索字符串的其余部分。

lowerBoundupperBound 是范围的不可变属性, 所以你必须创建一个新范围,从 match.upperBound.

开始

如果找不到匹配项,循环也应终止。 这可以通过移动绑定来实现 let match = ...进入where条件

var range = self.startIndex..<self.endIndex
while range.lowerBound < range.upperBound,
    let match = self.range(of: regex, options: .regularExpression, range: range) {
        print(match) // the matching range
        print(self.substring(with: match)) // the matched string

        range = match.upperBound..<self.endIndex
}

如果空字符串匹配,这仍然会导致无限循环 模式(例如 regex = "^")。这可以解决,但是 作为替代方案,使用 NSRegularExpression 获取所有的列表 匹配项(参见示例 )。