I want to extract substrings from a string that match a regex pattern.
So I\'m looking for something like this:
func matchesForRegexInText(regex: St
Big thanks to Lars Blumberg his answer for capturing groups and full matches with Swift 4, which helped me out a lot. I also made an addition to it for the people who do want an error.localizedDescription response when their regex is invalid:
extension String {
func matchingStrings(regex: String) -> [[String]] {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..
For me having the localizedDescription as error helped understand what went wrong with escaping, since it's displays which final regex swift tries to implement.