Regex for an email address doesn't work

后端 未结 8 2099
隐瞒了意图╮
隐瞒了意图╮ 2021-02-04 22:32

I\'m trying to check if some email address is correct with the following code :

NSPredicate *regexMail = [NSPredicate predicateWithFormat:@\"SELF MATCHES \'.*@.*         


        
相关标签:
8条回答
  • 2021-02-04 23:15

    This page has a good explanation of using regular expressions to validate email, as well as some regexes:

    http://www.regular-expressions.info/email.html

    Their expression:

    [a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
    

    Seems to be the best tradeoff between thoroughness and correctness.

    0 讨论(0)
  • 2021-02-04 23:18

    This is the regular expression used by the iOS Mail application to validate an email address:

    ^[[:alnum:]!#$%&’*+/=?^_`{|}~-]+((\.?)[[:alnum:]!#$%&’*+/=?^_`{|}~-]+)*@[[:alnum:]-]+(\.[[:alnum:]-]+)*(\.[[:alpha:]]+)+$
    

    And here is a copy/paste ready function using this regular expression to validate an email address in Objective-C:

    BOOL IsValidEmail(NSString *email)
    {
        // Regexp from -[NSString(NSEmailAddressString) mf_isLegalEmailAddress] in /System/Library/PrivateFrameworks/MIME.framework
        NSString *emailRegex = @"^[[:alnum:]!#$%&'*+/=?^_`{|}~-]+((\\.?)[[:alnum:]!#$%&'*+/=?^_`{|}~-]+)*@[[:alnum:]-]+(\\.[[:alnum:]-]+)*(\\.[[:alpha:]]+)+$";
        NSPredicate *emailPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
        return [emailPredicate evaluateWithObject:email];
    }
    
    0 讨论(0)
提交回复
热议问题