iOS中的电子邮件验证 - 正则表达式无法正常工作 - 代码包含有效电子邮件地址数组

时间:2015-06-12 13:25:18

标签: ios regex

我有一系列据称有效的电子邮件,我正在测试我的正则表达式语句以检查我的正则表达式方法是否有效。根据这个列表,他们应该全部返回,但有些不,我将如何弹出我的代码,以便相应地工作:

+(BOOL)isValidEmail: (NSString *)emailString{
    BOOL stricterFilter = YES;
    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:emailString];

}

有效电子邮件数组是:

 NSArray *array = [NSArray arrayWithObjects:@"johndoe@gmail.com",

                  @"email@example.com",
                  @"firstname.lastname@example.com",
                  @"email@subdomain.example.com",
                  @"firstname+lastname@example.com",
                  @"email@123.123.123.123",
                  @"email@[123.123.123.123]",
                  @"“email”@example.com",
                  @"1234567890@example.com",
                  @"email@example-one.com",
                  @"_______@example.com",
                  @"email@example.name",
                  @"email@example.museum",
                  @"email@example.co.jp",
                  @"firstname-lastname@example.com",
                  nil];

然后我执行这个循环:

for (NSString * email in array) {
    NSLog(@"Email: %@ is valid %@",email,[NSString isValidEmail:email] ? @"YES" : @"NO");
    ;
}

哪些日志:

 Email: johndoe@gmail.com is valid YES
 Email: email@example.com is valid YES
 Email: firstname.lastname@example.com is valid YES
 Email: email@subdomain.example.com is valid YES
 Email: firstname+lastname@example.com is valid YES
 Email: email@123.123.123.123 is valid NO
 Email: email@[123.123.123.123] is valid NO
 Email: /“email/”@example.com is valid NO
 Email: 1234567890@example.com is valid YES
 Email: email@example-one.com is valid YES
 Email: _______@example.com is valid YES
 Email: email@example.name is valid YES
 Email: email@example.museum is valid NO
 Email: email@example.co.jp is valid YES
 Email: firstname-lastname@example.com is valid YES

根据Valid email addresses

,它们都应该有效

1 个答案:

答案 0 :(得分:1)

试试这个:

[\da-zA-Z_+\\.\-\/(“|”)]+@(([a-zA-Z\-]+(\\.[a-zA-Z]+){1,2})|(\[?[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\]?))