Skip to content

Instantly share code, notes, and snippets.

@littlebobert
Created September 24, 2015 17:02
Show Gist options
  • Save littlebobert/262047a32dccc7b73458 to your computer and use it in GitHub Desktop.
Save littlebobert/262047a32dccc7b73458 to your computer and use it in GitHub Desktop.
class func matchesForRegexInText(regex: String!, text: String!, captureGroupIndices:[Int]) -> [[String]] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [.CaseInsensitive])
let nsString = text as NSString
let results = regex.matchesInString(text, options: [], range: NSMakeRange(0, nsString.length))
return results.map { (textCheckingResult:NSTextCheckingResult) -> [String] in
var returnValue = [String]()
returnValue.append(nsString.substringWithRange(textCheckingResult.range))
if textCheckingResult.numberOfRanges != captureGroupIndices.count + 1 {
return returnValue
}
for captureGroupIndex in captureGroupIndices {
returnValue.append(nsString.substringWithRange(textCheckingResult.rangeAtIndex(captureGroupIndex)))
}
return returnValue
}
} catch _ {
assert(false, "Invalid regular expression: \(regex)")
}
return []
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment