NSRegularExpression validate email

14,626

Solution 1

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 = @"[email protected]";
 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");
    }

Solution 2

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.

Share:
14,626
s4lfish
Author by

s4lfish

Updated on July 21, 2022

Comments

  • s4lfish
    s4lfish almost 2 years

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

    Something like this pseudocode:

    - (BOOL)validateMail : (NSString *)email
    {
        NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"" options:NSRegularExpressionCaseInsensitive error:NULL];
    
        if(emailValidated)
        {
            return YES;
        }else{
            return NO;
        }
    }
    

    But i don't know how exactly i validate an NSString if it's looking like this one "[email protected]"

    Perhaps someone can help me here.

    Greetings s4lfish