NSRegularExpression cannot find group match capture

I am trying to parse a string using a single regex pattern.

Here is the template:

(\")(.+)(\")\s*(\{)

Here is the text to parse:

"base" {

I want to find these 4 capture groups:

1. "
2. base
3. "
4. {

I am using the following code trying to capture these groups

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
}

Unfortunately, he could find only one group with a range (0, 8)that is equal to: "base" {. Thus, he finds one group, which is a whole line instead of 4 groups.

Is it even possible to get these groups using NSRegularExpression?

+4
source share
1 answer

Yes, of course, it is possible. You just need to change your current logic to search for actual groups:

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

1 . , . , , .

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

esgeed regex , .

+6

Source: https://habr.com/ru/post/1598562/


All Articles