本文翻译自:How to validate an e-mail address in swift?
Does anyone know how to validate an e-mail address in Swift? 有谁知道如何在Swift中验证电子邮件地址? I found this code: 我发现此代码:
- (BOOL) validEmail:(NSString*) emailString {
if([emailString length]==0){
return NO;
}
NSString *regExPattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
NSLog(@"%i", regExMatches);
if (regExMatches == 0) {
return NO;
} else {
return YES;
}
}
but I can't translate it to Swift. 但我无法将其翻译为Swift。
#1楼
参考:https://stackoom.com/question/1isCQ/如何快速验证电子邮件地址
#2楼
I would use NSPredicate
: 我会用NSPredicate
:
func isValidEmail(emailStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: emailStr)
}
for versions of Swift earlier than 3.0: 对于低于3.0的Swift版本:
func isValidEmail(emailStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: emailStr)
}
for versions of Swift earlier than 1.2: 对于低于1.2的Swift版本:
class func isValidEmail(emailStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
if let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) {
return emailPred.evaluateWithObject(emailStr)
}
return false
}
#3楼
Here is a method based on rangeOfString
: 这是一个基于rangeOfString
的方法:
class func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
let result = range != nil ? true : false
return result
}
Note: updated TLD length. 注意:更新的TLD长度。
Here is the definitive RegEx for email as per RFC 5322, note that this is best not used because it only checks the basic syntax of email addresses and does not check is the top level domain exists. 这是根据RFC 5322定义的电子邮件正则表达式,请注意,最好不要使用它,因为它仅检查电子邮件地址的基本语法,而不检查是否存在顶级域。
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)* | "(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f] | \\[\x01-\x09\x0b\x0c\x0e-\x7f])*") @ (?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])? | \[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3} (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]: (?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f] | \\[\x01-\x09\x0b\x0c\x0e-\x7f])+) \])
See Regular-Expressions.info for more complete information on email RegExs. 见Regular-Expressions.info有关电子邮件RegExs更全面的信息。
Note that no escaping as required by a language such as Objective-C or Swift. 请注意,没有像Objective-C或Swift这样的语言必须进行转义。
#4楼
As a String
class extension 作为String
类扩展
SWIFT 4 SWIFT 4
extension String {
func isValidEmail() -> Bool {
// here, `try!` will always succeed because the pattern is valid
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)
return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
}
}
Usage 用法
if "rdfsdsfsdfsd".isValidEmail() {
}
#5楼
This is the updated version for Swift 2.0 - 2.2 这是Swift 2.0-2.2的更新版本
var isEmail: Bool {
do {
let regex = try NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .CaseInsensitive)
return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
} catch {
return false
}
}
#6楼
Here is a fuse of the two most up-voted answer with the correct regex: a String extension using predicate so you can call string.isEmail 这是正确答案的两个最受好评的答案的融合:使用谓词的String扩展,因此您可以调用string.isEmail
extension String {
var isEmail: Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,20}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluateWithObject(self)
}
}