字符串扩展,用于匹配正则表达式

时间:2019-06-22 18:35:35

标签: swift swift2 swift4 nsregularexpression swift4.2

我有2个用Swift 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
    }
}

第一个函数的返回是我无法解决的问题。 第三行是Swift 4中的if let range = self.range(of: expression, options: NSString.CompareOptions.regularExpression, range: nil, locale: nil){

在第二个功能中,我不知道字符如何迁移。

1 个答案:

答案 0 :(得分:3)

.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($0.range, in: self)!])
        }
    }
}

-更迅捷的风格:

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($0.range, in: self)!])
        }
    }

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