NSRegularExpression validate email

后端 未结 3 1705
长情又很酷
长情又很酷 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");
        }
    

提交回复
热议问题