I have a method for finding regular expressions in a 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 well. But if I have a regex product_title:\['(.*)', it returns me product_title:[\'Some title bla bla\', but I only need a part (.*).
I am new to swift, but in python this problem is solved using a function groups(). How to use capture group in swift. Please provide an example.
source
share