Nitish Nitish - 2 months ago 19
iOS Question

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?

Thanks,

Nitish

Answer

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:@"johndoe@example.com"] == YES) {
  // Okay
} else {
  // Not found
}

EDIT :

Because @dunforget got the best solution despites mine is the accepted one, please read his answer.