匹配正则表达式的字符串扩展

String extension for matching regular expression

我在 Swift 2 中编写了 2 个函数,但 Apple 强制我迁移到 Swift 4,我无法修复这些函数。

extension String {
    func stringsMatchingRegularExpression(expression: String) -> [String] {
        if let range = self.rangeOfString(expression, options: NSString.CompareOptions.RegularExpressionSearch, range: nil, locale: nil) {
            return [self[range]] + self[range.endIndex..<self.endIndex].stringsMatchingRegularExpression(expression)
        }
        return []
    }

    func stringsMatchingRegularExpressionLarge(expression: String) -> [String] {
        var result = [String]()
        var currentRange = self.characters.indices
        while let range = self.rangeOfString(expression, options: NSString.CompareOptions.RegularExpressionSearch, range: currentRange, locale: nil) {
            result.append(self[range])
            currentRange.startIndex = range.endIndex
        }
        return result
    }
}

第一个函数的return是我无法修复的问题。 第 3 行是 if let range = self.range(of: expression, options: NSString.CompareOptions.regularExpression, range: nil, locale: nil){ in Swift 4

在第二个函数中,我不知道.characters 是如何迁移的。

.characters都不见了。您可以直接使用字符串本身。

self.characters.indices更改为self.indices

self.rangeOfString(expression, options: NSString.CompareOptions.RegularExpressionSearch, range: nil, locale: nil)更改为self.range(of: expression, options: .regularExpression, range: nil, locale: nil)

最后,您可以使用 NSRegularExpression 而不是递归调用该函数,但请注意它可能 throw 一些错误,因此您应该以某种方式处理它。使用此扩展名:

extension String {
    func stringsMatchingRegularExpression(expression regex: String) throws -> [String] {
        let regex = try NSRegularExpression(pattern: regex)
        let results = regex.matches(in: self,
                                    range: NSRange(self.startIndex..., in: self))
        return results.map {
            String(self[Range([=10=].range, in: self)!])
        }
    }
}

- 更多 Swifty-Style:

extension String {

    func matching(expression regex: @autoclosure () throws -> NSRegularExpression) rethrows -> [String] {
        let results = try regex().matches(in: self, range: NSRange(self.startIndex..., in: self))
        return results.map {
            String(self[Range([=11=].range, in: self)!])
        }
    }

    func matching(pattern regexPattern: String) throws -> [String] {
        return try self.matching(expression: NSRegularExpression(pattern: regexPattern))
    }
}