Created
June 3, 2014 06:53
-
-
Save marklarr/d1032a1ffd493de8284c to your computer and use it in GitHub Desktop.
Ruby-esque regex in Swift
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
// Regex | |
import Foundation | |
operator infix =~ {} | |
@infix func =~ (str: String, pattern: String) -> Bool { | |
var error: NSError? | |
let regex = NSRegularExpression.regularExpressionWithPattern(pattern, options: nil, error: &error) | |
if (error) { return false } | |
return regex.numberOfMatchesInString(str, options: nil, range: NSMakeRange(0, countElements(str))) > 0 | |
} | |
"Ayaka" =~ "^A.*" // true | |
"Ayaka" =~ "Mickey" // false | |
"Mark" =~ "M..k(ey)?" // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice.
Please note that overriding
= instead of =will allow using Regexps in switch statements :-)(Ref. "Expression Pattern" in The Swift Programming Language)