Last active
June 4, 2020 13:00
-
-
Save feighter09/d731cad53bd3622b8361 to your computer and use it in GitHub Desktop.
Swift: Switch on Regex! Aggregated from http://www.lesstroud.com/swift-using-regex-in-switch-statements/ and http://nshipster.com/swift-literal-convertible/
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
struct Regex { | |
let pattern: String | |
let options: NSRegularExpressionOptions | |
private var matcher: NSRegularExpression { | |
return try! NSRegularExpression(pattern: pattern, options: options) | |
} | |
init(pattern: String, options: NSRegularExpressionOptions! = nil) | |
{ | |
self.pattern = pattern | |
self.options = options ?? [] | |
} | |
func match(string: String, options: NSMatchingOptions = []) -> Bool | |
{ | |
let entireRange = NSMakeRange(0, string.characters.count) | |
let matches = matcher.numberOfMatchesInString(string, options: options, range: entireRange) | |
return matches > 0 | |
} | |
} | |
protocol RegularExpressionMatchable { | |
func match(regex: Regex) -> Bool | |
} | |
extension String: RegularExpressionMatchable { | |
func match(regex: Regex) -> Bool { | |
return regex.match(self) | |
} | |
} | |
func ~=<T: RegularExpressionMatchable>(pattern: Regex, matchable: T) -> Bool { | |
return matchable.match(pattern) | |
} | |
// That's it! Have fun using it like so: | |
switch inputString { | |
case Regex(pattern: "^4[0-9]{12}(?:[0-9]{3})?$"): | |
print("It's a Visa card") | |
case Regex(pattern: "^3[47][0-9]{13}$"): | |
print("It's American Express") | |
case Regex(pattern: "^5[1-5][0-9]{14}$"): | |
print("It's a MasterCard") | |
case Regex(pattern: "^6(?:011|5[0-9]{2})[0-9]{12}$"): | |
print("It's a Discover card") | |
default: | |
print("ERROR: Unknown card type") | |
} | |
switch inputString { | |
case Regex(pattern: "^clemson(\\su.+)?$", options: NSRegularExpressionOptions.CaseInsensitive): | |
print("GREAT School!! Awesome Team!") | |
case Regex(pattern: "^(u.+)?south carolina$", options: NSRegularExpressionOptions.CaseInsensitive): | |
print("I'm sorry.") | |
default: | |
print("Bless your heart.") | |
} | |
// Just note that switch cases only execute the first branch that's matched | |
// The string "heyyo" matches both regular expressions, but only the first branch is executed | |
switch "heyyo" { | |
case Regex(pattern: "o$"): | |
print("ends with o") | |
case Regex(pattern: "^h"): | |
print("starts with h") | |
default: | |
break | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment