Skip to content

Instantly share code, notes, and snippets.

@loiclefloch
Created June 16, 2015 16:41
Show Gist options
  • Save loiclefloch/1a5d3f782e6d96c01ef1 to your computer and use it in GitHub Desktop.
Save loiclefloch/1a5d3f782e6d96c01ef1 to your computer and use it in GitHub Desktop.
Simplify regex with Swift
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