Skip to content

Instantly share code, notes, and snippets.

@djtech42
Last active August 25, 2017 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djtech42/df62af5a90e22174d92116d7a3fb6323 to your computer and use it in GitHub Desktop.
Save djtech42/df62af5a90e22174d92116d7a3fb6323 to your computer and use it in GitHub Desktop.
Swift Regular Expression Checks Using Pattern Matching Examples
// *** 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