且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift提取正则表达式匹配

更新时间:2022-11-14 19:54:41

即使 matchesInString()方法将 String 作为第一个参数,
它在内部使用 NSString ,并且range参数必须使用 NSString 长度而不是Swift字符串长度给出
。否则,
将失败扩展字形集群,例如flags。

Even if the matchesInString() method takes a String as the first argument, it works internally with NSString, and the range parameter must be given using the NSString length and not as the Swift string length. Otherwise it will fail for "extended grapheme clusters" such as "flags".

Swift 4 (Xcode 9)开始,Swift标准的
库提供了在 Range< String.Index>
NSRange $ c $之间转换的函数c>。

As of Swift 4 (Xcode 9), the Swift standard library provides functions to convert between Range<String.Index> and NSRange.

func matches(for regex: String, in text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex)
        let results = regex.matches(in: text,
                                    range: NSRange(text.startIndex..., in: text))
        return results.map {
            String(text[Range($0.range, in: text)!])
        }
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

示例: