Refresh Range in Swift 3

I am trying to search Stringfor regexusing the following snippet (it is in the extension for 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?
    }
}

It will correctly find the first event, but then I don’t know how to change the range to the matching position in order to search for the rest of the line.

+4
source share
1 answer

lowerBoundand upperBoundare immutable range properties, so you need to create a new range starting at match.upperBound.

Also, the loop should end if no match is found. This can be achieved by moving the binding let match = ...to the where clause.

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).

+4

Source: https://habr.com/ru/post/1653454/