【问题标题】:Update a Range in Swift 3在 Swift 3 中更新范围
【发布时间】:2016-09-02 15:14:41
【问题描述】:

我正在尝试使用以下 sn-p 搜索 String 中的 regex(它位于 String 的扩展中):

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?
    }
}

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

【问题讨论】:

  • 你想在while 循环中做什么?即使您可以更新范围,这似乎也是一个无限循环。而且我认为使用NSRegularExpression 更干净
  • 点很好,有什么建议可以让这个循环工作吗?我也会看看NSRegularExpression
  • @MartinR:我最终使用了NSRegularExpression

标签: swift string range swift3


【解决方案1】:

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 获取所有列表 匹配(参见例如Swift extract regex matches)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    相关资源
    最近更新 更多