Created
August 23, 2016 11:53
-
-
Save radex/885f7fbea00a32e064543cac01b8e27f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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