我是使用Regex和NSPredicates的新手。我正在尝试将以下客观代码转换为swift,并且失败并出现以下错误:
'NSInvalidArgumentException',原因:'无法进行正则表达式匹配 对象SELF MATCHES“。+ @([A-Za-z0-9 - ] + \。)+ [A-Za-z] {2} [A-Za-z] *”。'
目标C代码:
- (BOOL)validateEmailWithString:(NSString*)userEmail
{
BOOL stricterFilter = NO;
NSString *stricterFilterString = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
NSString *laxString = @".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:userEmail];
}
等效的Swift代码
func validateEmail(withString userEmail: String) -> Bool {
let stricterFilter: Bool = false
let stricterFilterString: String = "[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}"
let laxString: String = ".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*"
let emailRegex: String = stricterFilter ? stricterFilterString : laxString
let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)
return emailTest.evaluate(with: emailTest)
}
此行发生异常:
return emailTest.evaluate(with: emailTest)
目标C代码工作正常,但在swift应用程序崩溃。有人可以帮帮我吗?
答案 0 :(得分:0)
请使用此行并测试
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluateWithObject(userEmail)
答案 1 :(得分:0)
试试这个
func validateEmailWithString(checkString : String) -> Bool {
let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
return emailPredicate.evaluate(with: checkString)
}