Created
June 16, 2015 16:41
-
-
Save loiclefloch/1a5d3f782e6d96c01ef1 to your computer and use it in GitHub Desktop.
Simplify regex with 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
import Foundation | |
infix operator =~ {} | |
func =~ (input: String, pattern: String) -> Bool { | |
return Regex(pattern).test(input) | |
} | |
class Regex { | |
let internalExpression: NSRegularExpression | |
let pattern: String | |
init(_ pattern: String) { | |
self.pattern = pattern | |
var error: NSError? | |
self.internalExpression = NSRegularExpression( | |
pattern: pattern, | |
options: nil,//NSRegularExpression.CaseInsensitive | |
error: &error | |
)! | |
} | |
func test(input: String) -> Bool { | |
let matches = self.internalExpression.matchesInString( | |
input, | |
options: nil, | |
range:NSMakeRange(0, count(input)) | |
) | |
return matches.count > 0 | |
} | |
static func isValidEmail(candidate: String) -> Bool { | |
let emailRegex = ".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*" | |
return candidate =~ emailRegex | |
} | |
static func isValidPhone(candidate: String) -> Bool { | |
let phoneRegex = "^(\\+)[0-9]{10,12}$" | |
return candidate =~ phoneRegex | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment