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

9jyewag0  于 2022-11-06  发布在  Swift
关注(0)|答案(1)|浏览(185)

我有2个功能写在斯威夫特2,但苹果迫使我迁移到斯威夫特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){
在第二个函数中,我不知道如何。字符迁移。

kmynzznz

kmynzznz1#

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

相关问题