如何使用swift对正则表达式进行分组

chr*_*hrs 16 regex swift

在正则表达式中,您可以将不同的匹配分组以轻松地"匹配"给定匹配.

while match != nil {
  match = source.rangeOfString(regex, options: .RegularExpressionSearch)
  if let m = match {
    result.append(source.substringWithRange(m)
      source.replaceRange(m, with: "") 
  }
}
Run Code Online (Sandbox Code Playgroud)

以上作品找到了一系列的匹配,但它不能告诉我这个组.例如,如果我搜索封装在""中的单词,我想匹配一个"单词",但很快就只能获取单词

是否有可能迅速这样做?

Nat*_*ook 33

使用正则表达式,Swift现在非常丑陋 - 我们希望很快能获得更多原生支持!NSRegularExpression你想要的方法是matchesInString.以下是如何使用它:

let string = "This is my \"string\" of \"words\"."
let re = NSRegularExpression(pattern: "\"(.+?)\"", options: nil, error: nil)!
let matches = re.matchesInString(string, options: nil, range: NSRange(location: 0, length: string.utf16Count))

println("number of matches: \(matches.count)")

for match in matches as [NSTextCheckingResult] {
    // range at index 0: full match
    // range at index 1: first capture group
    let substring = (string as NSString).substringWithRange(match.rangeAtIndex(1))
    println(substring)
}
Run Code Online (Sandbox Code Playgroud)

输出:

number of matches: 2
string
words
Run Code Online (Sandbox Code Playgroud)


zek*_*kel 7

如果要收集匹配的字符串,可以使用此选项. (我的答案来自Nate Cooks非常有帮助的答案.)

更新了Swift 2.1

extension String {
    func regexMatches(pattern: String) -> Array<String> {
        let re: NSRegularExpression
        do {
            re = try NSRegularExpression(pattern: pattern, options: [])
        } catch {
            return []
        }

        let matches = re.matchesInString(self, options: [], range: NSRange(location: 0, length: self.utf16.count))
        var collectMatches: Array<String> = []
        for match in matches {
            // range at index 0: full match
            // range at index 1: first capture group
            let substring = (self as NSString).substringWithRange(match.rangeAtIndex(1))
            collectMatches.append(substring)
        }
        return collectMatches
    }
}
Run Code Online (Sandbox Code Playgroud)

更新了Swift 3.0

extension String {
func regexMatches(pattern: String) -> Array<String> {
    let re: NSRegularExpression
    do {
        re = try NSRegularExpression(pattern: pattern, options: [])
    } catch {
        return []
    }

    let matches = re.matches(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count))
    var collectMatches: Array<String> = []
    for match in matches {
        // range at index 0: full match
        // range at index 1: first capture group
        let substring = (self as NSString).substring(with: match.rangeAt(1))
        collectMatches.append(substring)
    }
    return collectMatches
}}
Run Code Online (Sandbox Code Playgroud)