Created
February 14, 2019 11:10
-
-
Save ts95/2bdf53a84a08034766f0f737e03962e6 to your computer and use it in GitHub Desktop.
Some useful regex extension methods for the String type
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
// 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