Skip to content

Instantly share code, notes, and snippets.

@revolter
Forked from feighter09/Regex.swift
Last active June 4, 2020 13:02
Show Gist options
  • Save revolter/b791eb8c037c91b2be3af2abb75d625e to your computer and use it in GitHub Desktop.
Save revolter/b791eb8c037c91b2be3af2abb75d625e to your computer and use it in GitHub Desktop.
Swift: Switch on Regex! Adapted from https://gist.github.com/feighter09/d731cad53bd3622b8361
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