23

Can someone show me a sample RegEx for an email address and how to use in in Objective-C?

Looking for something that fits: name@place.something

jscs
  • 63,694
  • 13
  • 151
  • 195
Logan S.
  • 517
  • 1
  • 4
  • 15
  • the basic regular expression for the email is `^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$` – holex Aug 01 '12 at 13:54
  • 3
    @holex And it's wrong. The first error that I found is that it does not allow `+` to the left of the @. Don't bother trying to correct it, it's almost impossible. – JeremyP Aug 01 '12 at 14:00
  • @JeremyP do you know what the `+` sign means in a regular expression? :O it seems you don't. :( – holex Aug 01 '12 at 14:03
  • Here is a related Stackoverflow post with an answer containing a reference and example: http://stackoverflow.com/questions/845317/regex-solution-for-objective-c – John F. Aug 01 '12 at 13:55
  • @holex What I mean is that you are allowed (for instance) an address like `jeremyp+foo@example.com`. Your regular expression rejects that, I know because I tested it. – JeremyP Aug 01 '12 at 14:10
  • 2
    @holex *Please* read what I am saying. In fact better take your regular expression and the **valid** email address in my last comment and see if your RE matches. It doesn't. The `+` signs in your RE mean "repeat at least once". They do not mean "match a plus sign". **But plus signs are valid in the local name part of an email address** – JeremyP Aug 01 '12 at 14:16
  • 2
    @holex I don't have an omnipotent answer. I don't have one because email address validation with a regex is notoriously difficult to do. Your answer (well, not answer, but comment) was wrong. Why is it suddenly a crime to say so? – JeremyP Aug 01 '12 at 14:30
  • possible duplicate of [Using a regular expression to validate an email address](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address) – jscs Aug 01 '12 at 18:40
  • I wasn't sure if the same syntax was used for Objective C and Php – Logan S. Aug 01 '12 at 18:43

4 Answers4

43

As featured on: http://github.com/benofsky/DHValidation

- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 

    return [emailTest evaluateWithObject:candidate];
}

Or add the http://regexkit.sourceforge.net/RegexKitLite/ to your project and do the regex yourself like above.

Also to reply to the issue of checking if an e-mail address is actually real, not just works with regex you could use some service like: http://verify-email.org/register/levels.html

Please note this answer doesn't take into account the newer length TLDs such as .online; to include those update the final {2,4} to be {2,63}

Ryan McDonough
  • 9,732
  • 3
  • 55
  • 76
  • 1
    This is better than holex's but still wrong. `postmaster@com` is probably even a real address with a real mailbox. Also the local part (the bit to the left of the @) is allowed to be a quoted string. – JeremyP Aug 01 '12 at 14:07
  • 3
    the Apple's `NSRegularExpression` class does the same, no 3rd part code is necessary for this. – holex Aug 01 '12 at 14:09
  • @JeremyP it seems you still don't understand the regular expressions. :( please, provide a full answer for us, if you can... – holex Aug 01 '12 at 14:11
  • 5
    @holex I do understand regular expressions. It seems *you* don't understand the full syntax of a valid SMTP email address. I'm not going to provide a full answer because it is notoriously hard to do. – JeremyP Aug 01 '12 at 14:13
  • @JeremyP if you _really_ understand the regular expression you would not say that stupidity about the `+` sign, because **it is an operator only in the expression** and it will never validates such an email address you think (`jeremyp+foo@example.com`). this is a serious incompetence from you. :( – holex Aug 01 '12 at 14:21
  • 5
    @holex Go and look up the RFC and educate yourself as to the syntax of valid email addresses. The plus sign is allowed in the local name part. There is nothing wrong with the example email address that I gave. It's legal but your regex says it is not. Try this link for a summary http://en.wikipedia.org/wiki/Email_address – JeremyP Aug 01 '12 at 14:26
  • thank you for your arrogant and wiseacre style. your solution must be very helpful for everybody includes the asker. you should not be on this forum because you ruined everything without providing any useful. :( such people is being called troll. – holex Aug 01 '12 at 14:30
  • 4
    I hate to jump in here, but @JeremyP is right: validating an email address with a regex is notoriously difficult and pure folly. And there's really no point, as even a syntactically-legal email address might not point to an actual mailbox. This page has more info on using a regex; scroll down to the section called "The Official Standard" to see what the *real* regex is: http://www.regular-expressions.info/email.html – mipadi Aug 01 '12 at 14:40
  • 2
    @holex Telling people where their comments (you didn't make it an answer, why not?) are wrong is not trolling. As for whether I should be on this forum or not: well, I'll let my rep speak to that. – JeremyP Aug 01 '12 at 14:47
  • 1
    @JeremyP no matter how high your reputation is. it does not makes you better than a simple troll in this thread. that is it. I've tried to provide something, you have't provide any useful yet, however one answer has been accepted already. shame on you. :( – holex Aug 01 '12 at 14:54
  • 3
    @holex All I did was explain that your comment was incorrect. That does not make me a troll. I explained why your comment was incorrect, which is useful as it allows you or the questioner to fix the issue. I did not go round accusing people of not knowing regular expressions and I have not accused anybody of being a troll. Is it more constructive to explain a technical fault in an answer or to indulge in name calling? – JeremyP Aug 01 '12 at 15:01
  • @JeremyP yes, you are seeing well the difference: correcting a wrong answer is great thing but saying a criticism without any will to correct the criticised answer after even someone asked you to provide you vision of it and you refused it - it called pointless trolling. and on this thread exactly this happened, no one used your _professional_ comments - there was no such comment. I'm an idiot to argue with such a person... I hope you've understood the point, I know it is more complex than make full regular expression for the standards. I'm really sorry but I can't link any summary for it. :( – holex Aug 01 '12 at 15:16
  • 2
    @holex I told you one thing to do to correct your comment. I also strongly implied that nothing you could do would fully patch it up which implies that a regex solution is almost impossible to make work correctly. I then stated this explicitly in response to one of your previous challenges. I reiterate: all I have done is tell you where your answer was wrong. I have since then been subject to a stream of abuse from you. If you do this to everybody who criticises your comments here, you will end up emotionally exhausted. It's better to accept the criticism, learn and move on. – JeremyP Aug 01 '12 at 15:24
  • @JeremyP the trolling is not equal to criticise something. providing an better answer would have been the correct way from you but you didn't and couldn't do it and I bet you won't do it. it defines you, not me. it is simple as the 1 by 1. I have no hard feelings about this thread, I'm just simple sad and sorry for you and your behaviour. :( that is it. it is not a life or dead thing. – holex Aug 01 '12 at 15:37
  • 1
    @holex I criticised your comment that was incorrect. Your response was to post insults. I think that's all that needs to be said. – JeremyP Aug 01 '12 at 15:41
  • 1
    @JeremyP yep, and ask your friends to **vote up** your _great_ and _helpful_ comments. :D it seems you are in deeper as I ever though. :( I'm out. enjoy the life! – holex Aug 01 '12 at 15:52
  • 1
    @holex I have no idea who is voting up my comments. I do know who voted up your `NSRegularExpression` comment though since it was me. – JeremyP Aug 01 '12 at 16:04
  • @JeremyP does the inclusion of a link to a service which can verify an email address exists help with your note that regex on an e-mail is a moot point? – Ryan McDonough Aug 02 '12 at 08:30
  • 2
    @RyanMcDonough There is no automated way to determine if an email address exists. If you send an email to an address that doesn't exist, you should get a bounce back, but it is not guaranteed. – JeremyP Aug 02 '12 at 13:32
  • So, some guy with an email address jimmy@company.name.com will not be too happy – Steve Walsh Apr 19 '16 at 13:42
6
NSString *string= @"my@mail.com her@mail.com him@mail.com";
NSError *error = NULL;
NSRegularExpression *regex = nil;
regex = [NSRegularExpression regularExpressionWithPattern:@"\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,6}"
                                                  options:NSRegularExpressionCaseInsensitive
                                                    error:&error];   
NSUInteger numberOfMatches = 0;
numberOfMatches = [regex numberOfMatchesInString:string
                                         options:0
                                           range:NSMakeRange(0, [string length])];
NSLog(@"numberOfMatches is: %lu", numberOfMatches);

There are more options of course. Read here.

Avi Cohen
  • 3,102
  • 2
  • 25
  • 26
  • I don't know much about RegEx but will this work for domains that have compound TLD's? I think I've seen things like website.com.ca or something? Also wha about hy-ph-en-at-ed eMails? – Albert Renshaw Oct 20 '14 at 15:57
  • @AlbertRenshaw it wont match mail like hi@how.are.you, but it will match hyphenated like my-mail@mail.com – Avi Cohen Oct 21 '14 at 14:59
  • Limiting TLDs to 2 to 6 characters is very restricting. See official list of TLDs: http://www.iana.org/domains/root/db – Toto Oct 21 '14 at 17:56
  • @M42 This issue can be fixed easily by replacing {2,6} with {2,10} for example – Avi Cohen Oct 22 '14 at 17:34
  • Sure, but what about TLDs like `.சிங்கப்பூர்` or `.中國`? – Toto Oct 22 '14 at 17:39
  • +1 to Toto's comment, we're at 24 chars and need hypens included now. `curl "http://data.iana.org/TLD/tlds-alpha-by-domain.txt" | grep -v '#' | awk '{ if (length($0) > maxLen) { maxLen = length($0); maxString = $0; } } END { print maxLen; print maxString }'` – gav Dec 24 '15 at 02:38
5

As I couldn't find any serious email regex example for Objective-C, I am putting here this one:

const char cRegex[] = "^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$";
NSString *emailRegex = [NSString stringWithUTF8String:cRegex];
NSPredicate *emailPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES[c] %@", emailRegex];
BOOL isValid = [emailPredicate evaluateWithObject:email];

This is based on a regex by Michael Rushton, it is used by PHP's filter_var() function, and it seems to be good enough according to this comparison.

Enjoy!

Edit

Swift 4

func isValidEmail(email: String) -> Bool {
    let emailRegex = "^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$"
    return NSPredicate(format: "SELF MATCHES[c] %@", emailRegex).evaluate(with: email)
}
scope
  • 1,967
  • 14
  • 15
0

Regular expression for Invalid email format:

public static bool IsEmailValid(this string inputStr)
  {
    bool isValid = false;
    if (!string.IsNullOrWhiteSpace(inputStr))
     {
  isValid  = Regex.IsMatch(inputStr, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", 
                                    RegexOptions.IgnoreCase);
       }
    
         return isValid;
    
      }
Dev-lop-er
  • 578
  • 1
  • 7
  • 16
  • This doesn't match `me@localhost` (valid email) but matches `^@a.a` (invalid email). Please, have a look at these sites: [TLD list](https://www.iana.org/domains/root/db); [valid/invalid addresses](https://en.wikipedia.org/wiki/Email_address#Examples); [regex for RFC822 email address](http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html) – Toto Jul 28 '20 at 08:51