views:

110

answers:

6

Hi,

I'm trying to check if some email address is correct with the following code :

NSPredicate *regexMail = [NSPredicate predicateWithFormat:@"SELF MATCHES '.*@.*\..*'"];
if([regexMail evaluateWithObject:someMail])
... 

But the "\." doesn't seem to work since the mail "smith@company" is accepted. Besides, I have the following warning : "Unknown escape sequence"

Edit :

I'm programming in Objective-C for iPhone.

Thanks

+2  A: 

I guess it should be \\., since \ itself should be escaped as well.

Anton Gogolev
Already tried that, the warning disapeared, but the regex didn't work anyway. Will try the regex below. Thanks
Yoot
+1  A: 
FrustratedWithFormsDesigner
doesn't work...
Yoot
A: 

try putting double slash instead of one slash. that's what might the Unknown escape sequence mean.

here is a website that can help you understand how to use regex: http://www.wellho.net/regex/java.html

or just find the appropriate regex for email address here: http://regexlib.com/DisplayPatterns.aspx?cattabindex=0&categoryId=1

Saher
+1  A: 

You cannot correctly validate an email address with regular expressions alone. A simple search will show you many articles discussing this. The problem lies with the nature of DNS: there are too many possible domain names (including non-english and Unicode domains), you cannot correctly validate them using a regex. Don't try.

The only correct way to determine if an email address is valid is to send a message to the address with a unique URL that identifies the account associated with the email, for the user to click. Anything else will annoy your end-user.

Craig Trader
Yes, you're right, I'm only trying to do a simple check, just to see if the mail looks like "[email protected]" with "@" and "."
Yoot
In which case `..*[@]..*[.]..*` should cover your needs. I use `..*` to match at least one character, because `.+`, while more direct, isn't supported by all RegEx libraries. I use `[@]` and `[.]` because they will match a single character, without needing to deal with backslashes and double-backslashes for escaping a single character.
Craig Trader
Thanks a lot it works with ..*[@]..*[.]..*
Yoot
A: 

I think youre looking for this. Its a quite comprehensive listing of different regexps and a list of mail addresses for each, stating if the regexp was successful or not.

mizipzor
A: 

Here's a working example, with a slightly more appropriate pattern (although it's not perfect, as others have mentioned):

NSString* pattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
if ([predicate evaluateWithObject:@"[email protected]"] == YES) {
  // Match
} else {
  // No Match
}
Nathan de Vries
Still the same problem here with the caracter ".""johndoe@example" is matched but it shouldn't be.
Yoot