Skip to content

Instantly share code, notes, and snippets.

@mehmetfarhan
Last active July 6, 2020 07:38
Show Gist options
  • Save mehmetfarhan/0a79ce28030ae5b5673d47bc7c559b1d to your computer and use it in GitHub Desktop.
Save mehmetfarhan/0a79ce28030ae5b5673d47bc7c559b1d to your computer and use it in GitHub Desktop.
Regular Expressions
var email = "mehmetfarhan@gmail.com"
var pattern = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
// Using NSPredicate
var predicate = NSPredicate(format: "SELF MATCHES %@", pattern)
// Using range
var range = email.range(of: pattern, options: .regularExpression)
// Using NSRegularExpression
func checkIsValid(_ string: String, pattern: String) -> Bool {
let regex = try! NSRegularExpression(pattern: pattern, options: .dotMatchesLineSeparators)
let result = regex.firstMatch(
in: string,
options: NSRegularExpression.MatchingOptions(rawValue: .zero),
range: NSMakeRange(.zero, string.count)
)
guard result != nil else { return false }
return true
}
range != nil // true
predicate.evaluate(with: email) // true
checkIsValid(email, pattern: pattern) // true
print("\(email) is Valid Email ? \(range != nil)") // mehmetfarhan@gmail.com is Valid Email ? true
print("\(email) is Valid Email ? \(predicate.evaluate(with: email))") // mehmetfarhan@gmail.com is Valid Email ? true
print("\(email) is Valid Email ? \(checkIsValid(email, pattern: pattern))") // mehmetfarhan@gmail.com is Valid Email ? true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment