-
-
Save revolter/b791eb8c037c91b2be3af2abb75d625e to your computer and use it in GitHub Desktop.
Swift: Switch on Regex! Adapted from https://gist.github.com/feighter09/d731cad53bd3622b8361
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
protocol RegularExpressionMatchable { | |
func match(regex: NSRegularExpression) -> Bool | |
} | |
extension String: RegularExpressionMatchable { | |
func match(regex: NSRegularExpression) -> Bool { | |
let range = NSMakeRange(0, self.count) | |
let matches = regex.numberOfMatches(in: self, range: range) | |
return matches > 0 | |
} | |
} | |
func ~=<T: RegularExpressionMatchable>(pattern: NSRegularExpression, matchable: T) -> Bool { | |
return matchable.match(regex: pattern) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment