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.
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With