Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active August 29, 2015 14:17
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 JadenGeller/64f3e64ec629a6b718ab to your computer and use it in GitHub Desktop.
Save JadenGeller/64f3e64ec629a6b718ab to your computer and use it in GitHub Desktop.
Swift Regex
// Making the NSRegularExpression a little bit more pretty
typealias RegularExpression = NSRegularExpression
extension RegularExpression {
convenience init?(pattern: String, options: NSRegularExpressionOptions) {
self.init(pattern: pattern, options: options, error: nil)
}
convenience init?(pattern: String) {
self.init(pattern: pattern, options: nil, error: nil)
}
}
// Used to create regular expressions
prefix operator / { }
prefix func /(str: String) -> RegularExpression {
return RegularExpression(pattern: str)!
}
// Used to test strings against regex patterns
func ~=(regex: RegularExpression, str: String) -> Bool {
return regex.firstMatchInString(str, options: nil, range: NSRange(location: 0, length: (str as NSString).length)) != nil
}
// Example
func isFast(description: String) -> Bool {
switch description {
case /"quick|fast|speedy": return true
default: return false
}
}
isFast("The quick fox jumped over the lazy dog.") // -> true
isFast("The speedy tiger swam through the deep lagoon.") // -> true
isFast("The slow turtle crawled past the heavy rock.") // -> false
// Note you can also test outside of switch statements using the ~= operator
let name = "Jaden Geller"
if /"Jaden" ~= name {
println("Yay!") // -> "Yay!"
}
// Note you can also create your own more complicated regular expression, e.g.
// if RegularExpression(pattern: ..., options: ...) ~= testString { ... }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment