NSRegularExpression无法找到捕获组匹配项

Tom*_*ulc 5 regex ios capturing-group nsregularexpression swift

我正在尝试使用一个正则表达式模式解析字符串.

这是模式:

(\")(.+)(\")\s*(\{)
Run Code Online (Sandbox Code Playgroud)

这是要解析的文本:

"base" {
Run Code Online (Sandbox Code Playgroud)

我想找到这4个捕获组:

1. "
2. base
3. "
4. {
Run Code Online (Sandbox Code Playgroud)

我正在使用以下代码尝试捕获这些组

class func matchesInCapturingGroups(text: String, pattern: String) -> [String] {
    var results = [String]()

    let textRange = NSMakeRange(0, count(text))
    var index = 0

    if let matches = regexp(pattern)?.matchesInString(text, options: NSMatchingOptions.ReportCompletion, range: textRange) as? [NSTextCheckingResult] {
        for match in matches {
            // this match = <NSExtendedRegularExpressionCheckingResult: 0x7fac3b601fd0>{0, 8}{<NSRegularExpression: 0x7fac3b70b5b0> (")(.+)(")\s*(\{) 0x1}
            results.append(self.substring(text, range: match.range))
        }
    }

    return results
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,它只能找到一个范围(0, 8)等于的组:"base" {.所以它找到一个组,它是整个字符串而不是4个组.

是否有可能让这些群体使用NSRegularExpression

luk*_*302 7

是的,当然有可能.您只需要更改当前逻辑以查找实际组:

func matchesInCapturingGroups(text: String, pattern: String) -> [String] {
    var results = [String]()

    let textRange = NSMakeRange(0, text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))

    do {
        let regex = try NSRegularExpression(pattern: pattern, options: [])
        let matches = regex.matchesInString(text, options: NSMatchingOptions.ReportCompletion, range: textRange)

        for index in 1..<matches[0].numberOfRanges {
            results.append((text as NSString).substringWithRange(matches[0].rangeAtIndex(index)))
        }
        return results
    } catch {
        return []
    }
}

let pattern = "(\")(.+)(\")\\s*(\\{)"
print(matchesInCapturingGroups("\"base\" {", pattern: pattern))
Run Code Online (Sandbox Code Playgroud)

你实际上只得到1场比赛.你必须进入那场比赛,在那里你会找到被捕获的组.请注意,我省略了第一个组,因为第一个组代表整个匹配.

这将输出

[""","base",""","{"]

请注意转义的正则表达式字符串,并确保您使用相同的字符串.