Created
February 25, 2021 12:26
-
-
Save hechen/e8e69a5fc3458a6c82aec4bc14e5b5c6 to your computer and use it in GitHub Desktop.
String's regex matches 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 matches(for regexPattern: String) -> [[String]] { | |
do { | |
let text = self | |
let regex = try NSRegularExpression(pattern: regexPattern) | |
let matches = regex.matches(in: text, | |
range: NSRange(text.startIndex..., in: text)) | |
return matches.map { match in | |
return (0..<match.numberOfRanges).map { | |
let rangeBounds = match.range(at: $0) | |
guard let range = Range(rangeBounds, in: text) else { | |
return "" | |
} | |
return String(text[range]) | |
} | |
} | |
} catch let error { | |
print("invalid regex: \(error.localizedDescription)") | |
return [] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment