gpt4 book ai didi

ios - 如何快速验证电子邮件地址?

转载 作者:行者123 更新时间:2023-12-01 17:56:39 25 4
gpt4 key购买 nike

有人知道如何在 Swift 中验证电子邮件地址吗?我找到了这段代码:

- (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;
}
}

但我无法将其翻译为 Swift。

最佳答案

我会使用NSPredicate :

func isValidEmail(_ email: 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: email)
}

对于 3.0 之前的 Swift 版本:

func isValidEmail(email: 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: email)
}

对于 1.2 之前的 Swift 版本:

func isValidEmail(email: 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(email)
}
return false
}

关于ios - 如何快速验证电子邮件地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60701963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com