Last active
August 25, 2017 02:11
-
-
Save djtech42/df62af5a90e22174d92116d7a3fb6323 to your computer and use it in GitHub Desktop.
Swift Regular Expression Checks Using Pattern Matching Examples
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
// *** different ways a string can match using our pattern matching operator *** | |
enum StringMatchType { | |
case literal | |
case escapedRegularExpression | |
case regularExpression(withOptions: NSRegularExpression.Options) | |
} | |
/* *** example function that returns how the string matches against | |
a literal string and a regex pattern in default and case insensitive modes *** */ | |
func typeOfMatch(for string: String) -> StringMatchType? { | |
switch string { | |
case "regex is fun!": | |
return .literal | |
case "/.*is fun!/": | |
return .escapedRegularExpression | |
case RegexPattern(".*is fun!", options: .caseInsensitive): | |
return .regularExpression(withOptions: .caseInsensitive) | |
default: | |
return .none | |
} | |
} | |
// *** testing the switch statement *** | |
typeOfMatch(for: "regex is fun!") // matches literal "regex is fun!" | |
typeOfMatch(for: "swift is fun!") // matches escaped regex ".*is fun!" | |
typeOfMatch(for: "swift IS fun!") // matches case insensitive regex ".*is fun!" | |
typeOfMatch(for: "swift is really fun!") // no match, breaks the ".*is fun!" pattern |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment