Skip to content

Instantly share code, notes, and snippets.

@radex
Created August 23, 2016 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radex/885f7fbea00a32e064543cac01b8e27f to your computer and use it in GitHub Desktop.
Save radex/885f7fbea00a32e064543cac01b8e27f to your computer and use it in GitHub Desktop.
extension NSRegularExpression {
func capturedGroups(forString string: String) -> [String?]? {
let nsString = string as NSString
let stringRange = NSRange(location:0, length: nsString.length)
// Match
guard let result = firstMatchInString(string, options: [], range: stringRange) else {
return nil
}
// Iterate over captured groups
var groups: [String?] = []
for i in 0..<result.numberOfRanges {
let range = result.rangeAtIndex(i)
if range.location == NSNotFound {
groups.append(nil)
} else {
let substring = nsString.substringWithRange(range)
groups.append(substring)
}
}
return groups
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment