Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex capture group swift

I have a regex search method in string:

extension String {
    func searchRegex (regex: String) -> Array<String> {
        do {
            let regex = try NSRegularExpression(pattern: regex, options: NSRegularExpressionOptions(rawValue: 0))
            let nsstr = self as NSString
            let all = NSRange(location: 0, length: nsstr.length)
            var matches : Array<String> = Array<String>()
            regex.enumerateMatchesInString(self, options: NSMatchingOptions(rawValue: 0), range: all) {
                (result : NSTextCheckingResult?, _, _) in
                let theResult = nsstr.substringWithRange(result!.range)
                matches.append(theResult)
            }
            return matches
        } catch {
            return Array<String>()
        }
    }
}

It works good. But if i have a regular expression product_title:\['(.*)' it returns me product_title:[\'Some title bla bla\' but i only need the part (.*).

I'm new in swift, but in python this problem solved by using groups() function. How to use capture group in swift. Please give me example.

like image 335
Arti Avatar asked Jan 08 '23 07:01

Arti


1 Answers

NSTextCheckingResult has a numberOfRanges property and a rangeAtIndex() method that lets you grab the range for individual capture groups. So if you wanted the first capture group instead of the whole matched string, you would modify your code to:

        var matches : Array<String> = Array<String>()
        regex.enumerateMatchesInString(self, options: NSMatchingOptions(rawValue: 0), range: all) {(result : NSTextCheckingResult?, _, _) in
            let capturedRange = result!.rangeAtIndex(1)
            if !NSEqualRanges(capturedRange, NSMakeRange(NSNotFound, 0)) {
                let theResult = nsstr.substringWithRange(result!.rangeAtIndex(1))
                matches.append(theResult)
            }
        }
like image 71
Nate Cook Avatar answered Jan 09 '23 21:01

Nate Cook