Skip to content

Instantly share code, notes, and snippets.

@djtech42
Last active August 25, 2017 02:07
Show Gist options
  • Save djtech42/3e276403182611cfa599752dfc797812 to your computer and use it in GitHub Desktop.
Save djtech42/3e276403182611cfa599752dfc797812 to your computer and use it in GitHub Desktop.
Swift Regular Expression Checks Using Pattern Matching PatternMatchOperator
/* *** implementation for using the RegexPattern struct that can specify both a
regex pattern and options in pattern matching *** */
func ~=(lhs: RegexPattern, rhs: String) -> Bool {
return
try! NSRegularExpression(
pattern: lhs.pattern,
options: lhs.options
)
.numberOfMatches(
in: rhs,
options: [],
range: NSMakeRange(0, rhs.characters.count)
)
!= 0
}
/* *** implementation for using a string with forward slashes at the beginning and end
to specify a regular expression in pattern matching *** */
func ~=(lhs: String, rhs: String) -> Bool {
switch (lhs.characters.first, lhs.characters.last) {
case (Character("/")?, Character("/")?): // escaping slashes exist
return RegexPattern( // use regex matching
String(lhs.characters.dropFirst().dropLast()), // remove slashes
options: [] // zero options
) ~= rhs
default: // escaping slashes not used
return lhs == rhs // use literal matching
}
}
// *** testing the operators ***
if ".* is fun!" ~= "regex is fun!" {
print("literal match") // no output since the strings don't match in a literal sense
}
if "/.* is fun!/" ~= "regex is fun!" {
print("regex match")
/* prints "regex match" because the string is escaped with forward slashes
and the string to the right matches according to the regular expression */
}
if RegexPattern(".*is fun!", options: []) ~= "regex is fun!" {
print("regex match")
/* prints "regex match" because RegexPattern struct is used on the
left and string to the right matches according to the regular expression */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment