NSRegularExpression validate email

后端 未结 3 1704
长情又很酷
长情又很酷 2020-12-13 22:29

i want to use the NSRegularExpression Class to validate if an NSString is an email address.

Something like this pseudocode:



        
相关标签:
3条回答
  • 2020-12-13 22:47

    You can use:

    @"^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$";    // Edited: added ^ and $
    

    you can test it here:

    http://gskinner.com/RegExr/?2rhq7

    And save this link it will help you with Regex in the future:

    http://gskinner.com/RegExr/

    EDIT

    You can do it this way:

     NSString *string = @"shlaflaf@me.com";
     NSString *expression = @"^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$"; // Edited: added ^ and $
     NSError *error = NULL;
    
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:&error];
    
        NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
    
        if (match){
             NSLog(@"yes");
        }else{
             NSLog(@"no");
        }
    
    0 讨论(0)
  • 2020-12-13 22:47

    Swift 4 version

    I'm writing this for those who are doing Swift 4 version for email regular expression. The above can be done as follows:

     do {
            let emailRegex = try NSRegularExpression(pattern: "^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$", options: .caseInsensitive)
            let textRange = NSRange(location: 0, length: email.count)
            if emailRegex.firstMatch(in: email, options: [], range: textRange) != nil {
                //Do completion code here
            } else {
                //Do invalidation behaviour
            }
        } catch  {
             //Do invalidation behaviour
        }
    

    Assuming email is a swift String typed.

    0 讨论(0)
  • 2020-12-13 23:02

    This was an older question, but it's general enough to never go out of style.

    99.9% of email address regexs are wrong and even fewer handle international domains (IDN) properly.

    Trying to make a comprehensive email regex isn't a good use of development time or user CPU cycles.

    This is much simpler:

    1. Match [^@]+@([^@]+)

    2. Extract the domain per the matched part.

    3. Fail if it matches a banned domain. Cache the list of banned domains locally from a JSON endpoint so you don't have to wait for re-approval and can update it on-the-fly. (Be sure to log web stats for conversion analysis.)

    4. Check that the domain has DNS records. Check A and AAAA, in addition to MX, because not all domains implement MX. (Lame but true.)

    5. Just try to send the email already. The user will try again if they perceive an app has value. :))

    0 讨论(0)
提交回复
热议问题