Search code examples
iphoneiosnsdatadetector

Check email with NSDataDetector


I have a string coming from server and want to check whether it contains expressions like phone numbers, mail address and email. I got success in case of phone number and mail address, but not email. I am using NSDataDetector for this purpose. eg

NSString *string = sourceNode.label; //coming from server

//Phone number
NSDataDetector *phoneDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:nil]; 
NSArray *phoneMatches = [phoneDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];

for (NSTextCheckingResult *match in phoneMatches) {

    if ([match resultType] == NSTextCheckingTypePhoneNumber) {
        NSString *matchingStringPhone = [match description];
        NSLog(@"found URL: %@", matchingStringPhone);
    }
}  

But how to do the same for email?


Solution

  • EDIT:

    my answer has been accepted in 2012 and is pretty outdated. Please read please this one instead.

    Original post:

    In apple documentation, it seems that recognised types does not include email : http://developer.apple.com/library/IOs/#documentation/AppKit/Reference/NSTextCheckingResult_Class/Reference/Reference.html#//apple_ref/c/tdef/NSTextCheckingType

    So I suggest you to use a Regexp. It would be like :

    NSString* pattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]+";
    
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    if ([predicate evaluateWithObject:@"[email protected]"] == YES) {
      // Okay
    } else {
      // Not found
    }