Skip to content

Instantly share code, notes, and snippets.

@ts95
Created February 14, 2019 11:10
Show Gist options
  • Save ts95/2bdf53a84a08034766f0f737e03962e6 to your computer and use it in GitHub Desktop.
Save ts95/2bdf53a84a08034766f0f737e03962e6 to your computer and use it in GitHub Desktop.
Some useful regex extension methods for the String type
// MARK: - Regex extensions
extension String {
func test(for pattern: String, options: NSRegularExpression.Options = []) -> Bool {
guard let groups = try? matches(for: pattern, options: options) else { return false }
return groups.count >= 1
}
func matches(for pattern: String, options: NSRegularExpression.Options = []) throws -> [[String]] {
let regex = try NSRegularExpression(pattern: pattern, options: options)
let matches = regex.matches(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count))
let nsString = self as NSString
return matches.map { match in
return (0..<match.numberOfRanges).map { index in
let range = match.range(at: index)
return range.location != NSNotFound ? nsString.substring(with: range) : ""
}
}
}
func replacingOccurrences(ofPattern pattern: String, with replacement: String,
options: NSRegularExpression.Options = []) throws -> String {
let regex = try NSRegularExpression(pattern: pattern, options: options)
let matches = regex.matches(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count))
return matches.reversed().reduce(self) { (string, match) in
return (string as NSString).replacingCharacters(in: match.range, with: replacement)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment