Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

ios - NSRegularExpression validate email

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...