Created
December 18, 2017 07:02
-
-
Save max-potapov/0545b94d6a6d5bd2175bd3d4b01ba80f to your computer and use it in GitHub Desktop.
Capture groups from string with given pattern in Swift
This file contains 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 String { | |
func capturedGroups(withRegex pattern: String) -> [String]? { | |
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return nil } | |
let matches = regex.matches(in: self, options: [], range: NSRange(location: 0, length: count)) | |
guard let match = matches.first else { return nil } | |
let lastRangeIndex = match.numberOfRanges - 1 | |
guard lastRangeIndex >= 1 else { return nil } | |
var results = [String]() | |
for i in 1...lastRangeIndex { | |
let capturedGroupIndex = match.range(at: i) | |
let matchedString = (self as NSString).substring(with: capturedGroupIndex) | |
results.append(matchedString) | |
} | |
return results | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment