Last active
August 29, 2015 14:17
-
-
Save JadenGeller/64f3e64ec629a6b718ab to your computer and use it in GitHub Desktop.
Swift Regex
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
// 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