4025

Over the years I have slowly developed a regular expression that validates most email addresses correctly, assuming they don't use an IP address as the server part.

I use it in several PHP programs, and it works most of the time. However, from time to time I get contacted by someone that is having trouble with a site that uses it, and I end up having to make some adjustment (most recently I realized that I wasn't allowing four-character TLDs).

What is the best regular expression you have or have seen for validating emails?

I've seen several solutions that use functions that use several shorter expressions, but I'd rather have one long complex expression in a simple function instead of several short expression in a more complex function.

10

79 Answers 79

7
public bool ValidateEmail(string sEmail)
{
    if (sEmail == null)
    {
        return false;
    }

    int nFirstAT = sEmail.IndexOf('@');
    int nLastAT = sEmail.LastIndexOf('@');

    if ((nFirstAT > 0) && (nLastAT == nFirstAT) && (nFirstAT < (sEmail.Length - 1)))
    {
        return (Regex.IsMatch(sEmail, @"^[a-z|0-9|A-Z]*([_][a-z|0-9|A-Z]+)*([.][a-z|0-9|A-Z]+)*([.][a-z|0-9|A-Z]+)*(([_][a-z|0-9|A-Z]+)*)?@[a-z][a-z|0-9|A-Z]*\.([a-z][a-z|0-9|A-Z]*(\.[a-z][a-z|0-9|A-Z]*)?)$"));
    }
    else
    {
        return false;
    }
}
1
  • This will sometimes fail; a user in an email address may contain "@" characters if they are inside a quoted-string.
    – awwright
    Sep 11, 2020 at 5:18
7

I'm still using:

^[A-Za-z0-9._+\-\']+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$

But with IPv6 and Unicode coming up, perhaps this is best:

console.log(/^[\p{L}!#-'*+\-/\d=?^-~]+(.[\p{L}!#-'*+\-/\d=?^-~])*@[^@\s]{2,}$/u.test("תה.בועות@😀.fm"))

Gmail allows sequential dots, but Microsoft Exchange Server 2007 refuses them, which follows the most recent standard afaik.

7
  • Doesn't allow "John Smith"@example.com. Feb 12, 2013 at 23:27
  • True, but when is that actually needed? Feb 20, 2013 at 14:24
  • 2
    Any time an email address has a space in it? Feb 20, 2013 at 23:52
  • I've never seen one of those actually being used, and i think the official specs say it is only for backwards compatibility. Feb 21, 2013 at 11:50
  • Would you mind explaining what ^[A-Za-z0-9._+\-\']+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$ does exactly ?
    – me-me
    Nov 15, 2022 at 21:25
6

The regular expression for an email address is:

/^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u

This regular expression is 100% identical to the addr-spec ABNF for non-obsolete email addresses, as specified across RFC 5321, RFC 5322, and RFC 6532.

Additionally, you must verify:

  • The email address is well-formed UTF-8 (or ASCII, if you cannot send to internationalized email addresses)
  • The address is not more than 320 UTF-8 bytes
  • The user part (the first match group) is not more than 64 UTF-8 bytes
  • The domain part (the second match group) is not more than 255 UTF-8 bytes

The easiest way to do all of this is to use an existing function. In PHP, see the filter_var function using FILTER_VALIDATE_EMAIL and FILTER_FLAG_EMAIL_UNICODE (if you can send to internationalized email addresses):

$email_valid = filter_var($email_input, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE);

However, maybe you're building such a function—indeed the easiest way to implement this is to use a regular expression.

Remember, this only verifies that the email address will not cause a syntax error. The only way to verify that the address can receive email is to actually send an email.

Next, I will treat how you generate this regular expression.


I write a new answer, because most of the answers here make the mistake of either specifying a pattern that is too restrictive (and so have not aged well); or they present a regular expression that's actually matching a header for a MIME message, and not the email address itself.

It is entirely possible to make a regular expression from an ABNF, so long as there are no recursive parts.

RFC 5322 specifies what is legal to send in a MIME message; consider this the upper bound on what is a legal email address.

However, to follow this ABNF exactly would be a mistake: this pattern technically represents how you encode an email address in a MIME message, and allows strings not part of the email address, like folding whitespace and comments; and it includes support for obsolete forms that are not legal to generate (but that servers read for historical reasons). An email address does not include these.

RFC 5322 explains:

Both atom and dot-atom are interpreted as a single unit, comprising the string of characters that make it up. Semantically, the optional comments and FWS surrounding the rest of the characters are not part of the atom; the atom is only the run of atext characters in an atom, or the atext and "." characters in a dot-atom.

In some of the definitions, there will be non-terminals whose names start with "obs-". These "obs-" elements refer to tokens defined in the obsolete syntax in section 4. In all cases, these productions are to be ignored for the purposes of generating legal Internet messages and MUST NOT be used as part of such a message.

If you remove CFWS, BWS, and obs-* rules from the addr-spec in RFC 5322, and perform some optimization on the result (I used "greenery"), you can produce this regular expression, quoted with slashes and anchored (suitable for use in ECMAScript and compatible dialects, with added newline for clarity):

/^("(?:[!#-\[\]-~]|\\[\t -~])*"|[!#-'*+\-/-9=?A-Z\^-~](?:\.?[!#-'*+\-/-9=?A-Z\^-~])*)
@([!#-'*+\-/-9=?A-Z\^-~](?:\.?[!#-'*+\-/-9=?A-Z\^-~])*|\[[!-Z\^-~]*\])$/

This only supports ASCII email addresses. To support RFC 6532 Internationalized Email Addresses, replace the ~ character with \u{10FFFF} (PHP, ECMAScript with the u flag), or \uFFFF (for UTF-16 implementations, like .NET and older ECMAScript/JavaScript):

/^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u

This works, because the ABNF we are using is not recursive, and so forms a non-recursive, regular grammar that can be converted into a regular expression.

It breaks down like so:

  • The user part (before the @) may be a dot-atom or a quoted-string
  • "([!#-\[\]-~]|\\[\t -~])*" specifies the quoted-string form of the user, e.g. "root@home"@example.com. It permits any non-control character inside double quotes; except that spaces, tabs, double quotes, and backslashes must be backslash-escaped.
  • [!#-'*+\-/-9=?A-Z\^-~] is the first character of the dot-atom of the user.
  • (\.?[!#-'*+\-/-9=?A-Z\^-~])* matches the rest of the dot-atom, allowing dots (except after another dot, or as the final character).
  • @ denotes the domain.
  • The domain part may be a dot-atom or a domain-literal.
  • [!#-'*+\-/-9=?A-Z\^-~](\.?[!#-'*+\-/-9=?A-Z\^-~])* is the same dot-atom form as above, but here it represents domain names and IPv4 addresses.
  • \[[!-Z\^-~]*\] will match IPv6 addresses and future definitions of host names.

This regular expression allows all specification-compliant email addresses, and can be used verbatim in a MIME message (except for line length limits, in which case folding whitespace must be added).

This also sets non-capturing groups such that match[1] will be the user, match[2] will be the host. (However if match[1] starts with a double quote, then filter out backslash escapes, and the start and end double quotes: "root"@example.com and root@example.com identify the same inbox.)

Finally, note that RFC 5321 sets limits on how long an email address may be. The user part may be up to 64 bytes, and the domain part may be up to 255 bytes. Including the @ character, the limit for the entire address is 320 bytes. This is measured in bytes after the address is UTF-8 encoded; not characters.

Note that RFC 5322 ABNF defines a permissive syntax for domain names, allowing names currently known to be invalid. This also allows for domain names that could become legal in the future. This should not be a problem, as this should be handled the same way a non-existent domain name is.

Always consider the possibility that a user typed in an email address that works, but that they do not have access to. The only foolproof way to verify an email address is to send an email.

This is adapted from my article E-Mail Addresses & Syntax.

4
  • 1
    I can use this in javascript, but can't get it formatted for C# use. I've tried putting it into regex101 website and it says its invalid May 12, 2021 at 21:52
  • 1
    @PostImpatica What is the error, exactly? Regex101 expects a regular expression that is slash-delimited. I don't know which dialect C# expects. If your dialect is slash-delimited, you'll need to escape the slashes with a backslash.
    – awwright
    May 17, 2021 at 2:21
  • "John Smith"@example.com doesn't work with these on regexr.com Nov 19, 2022 at 0:32
  • 1
    @CeesTimmerman Spaces must be escaped in the quoted form, see rfc-editor.org/rfc/rfc5322#section-3.2.4 This is mentioned in my post: "It permits any non-control character inside double quotes; except that spaces, tabs, double quotes, and backslashes must be backslash-escaped." Note that whitespace is not considered "printing" in ASCII, see the VCHAR production in rfc-editor.org/rfc/rfc5234#appendix-B.1
    – awwright
    Nov 20, 2022 at 2:13
6

I don't believe the claim made by bortzmeyer that "The grammar (specified in RFC 5322) is too complicated for that" (to be handled by a regular expression).

Here is the grammar (from 3.4.1. Addr-Spec Specification):

addr-spec       =   local-part "@" domain
local-part      =   dot-atom / quoted-string / obs-local-part
domain          =   dot-atom / domain-literal / obs-domain
domain-literal  =   [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
dtext           =   %d33-90 /          ; Printable US-ASCII
                    %d94-126 /         ;  characters not including
                    obs-dtext          ;  "[", "]", or "\"

Assuming that dot-atom, quoted-string, obs-local-part, obs-domain are themselves regular languages, this is a very simple grammar. Just replace the local-part and domain in the addr-spec production with their respective productions, and you have a regular language, directly translatable to a regular expression.

4
  • 5
    You should investigate CFWS before you start making assumptions here. It's a nightmare.
    – rjbs
    Dec 16, 2009 at 19:07
  • CFWS = (1*([FWS] comment) [FWS]) / FWS. Still, I see no rule that makes the language not regular. It's complicated, for sure, but a complicated regular expression could handle it nevertheless. Jan 3, 2010 at 21:53
  • 3
    This doesn't answer the question. It's in response to another answer.
    – Luna
    Dec 5, 2016 at 20:17
  • CFWS is not part of the email address, it's part of the MIME syntax. See my answer stackoverflow.com/a/63841473/7117939 for why this is.
    – awwright
    Sep 12, 2020 at 23:38
6

I know this question is about regular expressions, but I am guessing that 90% of all developers reading these solutions are trying to validate an email address in an HTML form displayed in a browser.

If this is the case, I'd suggest checking out the new HTML5 <input type="email"> form element:

HTML5:

 <input type="email" required />

CSS 3:

 input:required {
      background-color: rgba(255, 0, 0, 0.2);
 }

 input:focus:invalid {
     box-shadow: 0 0 1em red;
     border-color: red;
 }

 input:focus:valid {
     box-shadow: 0 0 1em green;
     border-color: green;
 }

It is at HTML5 Form Validation Without JS - JSFiddle - Code Playground.

This has a couple of advantages:

  1. Automatic validation and no custom solution needed: simple and easy to implement
  2. No JavaScript, and no problems if JavaScript has been disabled
  3. No server has to calculate anything for that
  4. The user has immediate feedback
  5. Old browsers should automatically fallback to input type "text"
  6. Mobile browsers can display a specialized keyboard (@-Keyboard)
  7. Form validation feedback is very easy with CSS 3

The apparent downside might be missing validation for old browsers, but that'll change over time. I'd prefer this over any of these insane regular expression masterpieces.

Also see:

2
  • The other down side is that this is client-side only. Good for providing a smooth user experience, bad for validating data.
    – acrosman
    Jan 21, 2014 at 21:44
  • The problem with the default email validation is that it has lots of false positives. You'd need to use my complete pattern to eliminate all false positives while preventing false negatives from sneaking in. That pattern can be added via the pattern attribute. See my post for more info.
    – Joeytje50
    Jun 7, 2014 at 1:51
6

I use multi-step validation. As there isn't any perfect way to validate an email address, a perfect one can't be made, but at least you can notify the user he/she is doing something wrong - here is my approach:

  1. I first validate with the very basic regex which just checks if the email contains exactly one @ sign and it is not blank before or after that sign. e.g. /^[^@\s]+@[^@\s]+$/

  2. if the first validator does not pass (and for most addresses it should although it is not perfect), then warn the user the email is invalid and do not allow him/her to continue with the input

  3. if it passes, then validate against a more strict regex - something which might disallow valid emails. If it does not pass, the user is warned about a possible error, but the user is allowed to continue. Unlike step (1) where the user is not allowed to continue because it is an obvious error.

So in other words, the first liberal validation is just to strip obvious errors and it is treated as "error". People type a blank address, address without @ sign and so on. This should be treated as an error. The second one is more strict, but it is treated as a "warning" and the user is allowed to continue with the input, but warned to at least examine if he/she entered a valid entry. The key here is in the error/warning approach - the error being something that can't under 99.99% circumstances be a valid email.

Of course, you can adjust what makes the first regex more liberal and the second one more strict.

Depending on what you need, the above approach might work for you.

2
  • Technically, email can contain more than 1 @. It's an astonishing weird discovery i made recently. EG: "very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com Apr 18, 2022 at 18:57
  • 1
    Agreed, but I never claimed my method is 100% foolproof. It works in most cases. You gotta be realistic at some point and discard very unlikely cases. Most email addresses are something@something.something. If someone actually chooses to use an email address which is uses the most liberal syntax of all, he/she is in for a real treat of issues with various server/client programs not properly validating or allowing such email, or simply not working at all while sending/receiving. Where then such a user would be forced to use more "standard" syntax to ensure it works everywhere.
    – Coder12345
    Apr 18, 2022 at 23:16
5

This rule matches what our Postfix server could not send to.

Allow letters, numbers, -, _, +, ., &, /, and !

No -foo@bar.com

No asd@-bar.com

/^([a-z0-9\+\._\/&!][-a-z0-9\+\._\/&!]*)@(([a-z0-9][-a-z0-9]*\.)([-a-z0-9]+\.)*[a-z]{2,})$/i
5

For me the right way for checking email addresses is:

  1. Check that symbol @ exists, and before and after it there are some non-@ symbols: /^[^@]+@[^@]+$/
  2. Try to send an email to this address with some "activation code".
  3. When the user "activated" his/her email address, we will see that all is right.

Of course, you can show some warning or tooltip in front-end when the user typed a "strange" email to help him/her to avoid common mistakes, like no dot in the domain part or spaces in name without quoting and so on. But you must accept the address "hello@world" if user really want it.

Also, you must remember that the email address standard was and can evolve, so you can't just type some "standard-valid" regexp once and for all times. And you must remember that some concrete internet servers can fail some details of common standard and in fact work with own "modified standard".

So, just check @, hint user on frontend and send verification emails on the given address.

4

We have used http://www.aspnetmx.com/ with a degree of success for a few years now. You can choose the level you want to validate at (e.g. syntax check, check for the domain, MX records or the actual email).

For front-end forms we generally verify that the domain exists and the syntax is correct, and then we do stricter verification to clean out our database before doing bulk mail-outs.

2
  • The link is broken (it times out) - "Unable to connect. An error occurred during a connection to www.aspnetmx.com." Feb 13, 2022 at 14:53
  • This was originally answered in the year 2008. :-) Where has the time gone....
    – cbp
    Feb 14, 2022 at 7:03
4

This is one of the regexes for email:

^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$
1
  • It looks like line noise. Do you have an explanation and/or reference for it? Feb 13, 2022 at 15:06
4

For PHP I'm using the email address validator from the Nette Framework:

/* public static */ function isEmail($value)
{
    $atom = "[-a-z0-9!#$%&'*+/=?^_`{|}~]"; // RFC 5322 unquoted characters in local-part
    $localPart = "(?:\"(?:[ !\\x23-\\x5B\\x5D-\\x7E]*|\\\\[ -~])+\"|$atom+(?:\\.$atom+)*)"; // Quoted or unquoted
    $alpha = "a-z\x80-\xFF"; // Superset of IDN
    $domain = "[0-9$alpha](?:[-0-9$alpha]{0,61}[0-9$alpha])?"; // RFC 1034 one domain component
    $topDomain = "[$alpha](?:[-0-9$alpha]{0,17}[$alpha])?";
    return (bool) preg_match("(^$localPart@(?:$domain\\.)+$topDomain\\z)i", $value);
}
4

Just about every regular expression I've seen - including some used by Microsoft will not allow the following valid email to get through: simon-@hotmail.com

I just had a real customer with an email address in this format who couldn't place an order.

Here's what I settled on:

  • A minimal regular expression that won't have false negatives. Alternatively use the MailAddress constructor with some additional checks (see below):
  • Checking for common typos .cmo or .gmial.com and asking for confirmation "Are you sure this is your correct email address. It looks like there may be a mistake." Allow the user to accept what they typed if they are sure.
  • Handling bounces when the email is actually sent and manually verifying them to check for obvious mistakes.

try
{
    var email = new MailAddress(str);

    if (email.Host.EndsWith(".cmo"))
    {
        return EmailValidation.PossibleTypo;
    }

    if (!email.Host.EndsWith(".") && email.Host.Contains("."))
    {
        return EmailValidation.OK;
    }
}
catch
{
    return EmailValidation.Invalid;
}
5
  • 1
    This answer is misleading and unrelated to question. Allowing users to enter wrong email is a business decision, question is about validating it with regex. Mar 23, 2017 at 21:36
  • 1
    The first answer to this post does pass simon-@hotmail.com just fine. Jun 3, 2021 at 5:33
  • What programming language? C#? Java? Something else? Feb 14, 2022 at 23:37
  • The .gmial.com example is not in the example code. Feb 14, 2022 at 23:39
  • I have never ever seen "Gmail" misspelled as "Gmial". Feb 14, 2022 at 23:45
4

According to RFC 2821 and RFC 2822, the local-part of an email addresses may use any of these ASCII characters:

  1. Uppercase and lowercase letters
  2. The digits 0 through 9
  3. The characters, !#$%&'*+-/=?^_`{|}~
  4. The character "." provided that it is not the first or last character in the local-part.

Matches:

  • a&d@somedomain.com
  • a*d@somedomain.com
  • a/d@somedomain.com

Non-Matches:

  • .abc@somedomain.com
  • abc.@somedomain.com
  • a>b@somedomain.com

For one that is RFC 2821 and 2822 compliant, you can use:

^((([!#$%&'*+\-/=?^_`{|}~\w])|([!#$%&'*+\-/=?^_`{|}~\w][!#$%&'*+\-/=?^_`{|}~\.\w]{0,}[!#$%&'*+\-/=?^_`{|}~\w]))[@]\w+([-.]\w+)*\.\w+([-.]\w+)*)$

Email - RFC 2821, 2822 Compliant

1
  • Why doesn't it work on Håkan.Söderström@malmö.se ? Nov 19, 2022 at 0:17
4

Although very detailed answers are already added, I think those are complex enough for a developer who is just looking for a simple method to validate an email address or to get all email addresses from a string in Java.

public static boolean isEmailValid(@NonNull String email) {
    return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

As per the regular expression is concerned, I always use this regular expression, which works for my problems.

"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}"

If you are looking to find all email addresses from a string by matching the email regular expression. You can find a method at this link.

2
  • Re "which works for my problems.": What would those problems be? What are some examples of false positives and false negatives? How do you handle those? Feb 15, 2022 at 0:12
  • What programming language? Java? This was comment number 2 and question number 2. Feb 15, 2022 at 0:14
4

I always use the below regular expression to validate the email address. It covers all formats of email addresses based on English language characters.

"\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";

Given below is a C# example:

Add the assembly reference:

using System.Text.RegularExpressions;

and use the below method to pass the email address and get a boolean in return

private bool IsValidEmail(string email) {
    bool isValid = false;
    const string pattern = @"\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";

    isValid = email != "" && Regex.IsMatch(email, pattern);

    // Same above approach in multiple lines
    //
    //if (!email) {
    //    isValid = false;
    //} else {
    //    // email param contains a value; Pass it to the isMatch method
    //    isValid = Regex.IsMatch(email, pattern);
    //}
    return isValid;
}

This method validates the email string passed in the parameter. It will return false for all cases where param is null, empty string, undefined or the param value is not a valid email address. It will only return true when the param contains a valid email address string.

4
  • 2
    Does this code accept "Håkan.Söderström@malmö.se" or "试@例子.测试.مثال.آزمایشی" emails?
    – Ivan Z
    Mar 27, 2014 at 23:07
  • 3
    It's for standard Email Servers with standard characters. In case of non English language one should have to make its own customized ReGex. Mar 28, 2014 at 5:55
  • Regex and email spec includes UTF-8, hence illogical response.
    – rob2d
    Nov 30, 2019 at 3:05
  • 1
    In what way is it the best regular expression? Most comprehensive? Simplest? Fewest false negatives? Fewest false positives? The fastest? Fewest number of user complaints in actual real-world use? Some combination of these properties? Something else? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today). Feb 14, 2022 at 21:05
3

I would not suggest to use an regex at all - email addresses are way too complicated for that. This is a common problem so I would guess there are many libraries that contain a validator - if you use Java the EmailValidator of apache commons validator is a good one.

3

No one mentioned the issue of localization (i18n). What if you have clients coming from all over the world?

You will need to then need to sub-categorize your regex per country/area, which I have seen developers ending up building a large dictionary or configuration. Detecting the users' browser language setting may be a good starting point.

3

Here is the one I've build. It is not a bulletproof version, but it is 'simple' and checks almost everything.

[\w+-]+(?:\.[\w+-]+)*@[\w+-]+(?:\.[\w+-]+)*(?:\.[a-zA-Z]{2,4})

I think an explanation is in place so you can modify it if you want:

(e) [\w+-]+ matches a-z, A-Z, _, +, - at least one time

(m) (?:\.[\w+-]+)* matches a-z, A-Z, _, +, - zero or more times but need to start with a . (dot)

@ = @

(i) [\w+-]+ matches a-z, A-Z, _, +, - at least one time

(l) (?:\.[\w+-]+)* matches a-z, A-Z, _, +, - zero or more times but need to start with a . (dot)

(com) (?:\.[a-zA-Z]{2,4}) matches a-z, A-Z for 2 to 4 times starting with a . (dot)

giving e(.m)@i(.l).com where (.m) and (.l) are optional but also can be repeated multiple times.

I think this validates all valid email addresses, but blocks potential invalid without using an overcomplex regular expression which won't be necessary in most cases.

Notice this will allow +@-.com, but that is the compromise for keeping it simple.

1
  • Thanks! This worked for me. Here is a tested C/C++ escaped version used with Qt5: QRegExp rx("[\\w+-]+(?:\\.[\\w+-]+)*@[\\w+-]+(?:\\.[\\w+-]+)*(?:\\.[a-zA-Z]{2,})"); Jun 17, 2013 at 13:15
3

I’ve had a similar desire: wanting a quick check for syntax in email addresses without going overboard (the Mail::RFC822::Address answer which is the obviously correct one) for an email send utility. I went with this (I’m a POSIX regular expression person, so I don’t normally use \d and such from PCRE, as they make things less legible to me):

preg_match("_^[-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*@[0-9A-Za-z]([-0-9A-Za-z]{0,61}[0-9A-Za-z])?(\.[0-9A-Za-z]([-0-9A-Za-z]{0,61}[0-9A-Za-z])?)*\$_", $adr)

This is RFC-correct, but it explicitly excludes the obsolete forms as well as direct IP addresses (IP addresses and legacy IP addresses both), which someone in the target group of that utility (mostly: people who bother us in #sendmail on IRC) would not normally want or need anyway.

IDNs (internationalised domain names) are explicitly not in the scope of email: addresses like “foo@cäcilienchor-bonn.de” must be written “foo@xn--ccilienchor-bonn-vnb.de” on the wire instead (this includes mailto: links in HTML and such fun), only the GUI is allowed to display (and accept then convert) such names to (and from) the user.

2
  • Re "legacy IP addresses": Do you mean IPv4 IP addresses? Feb 13, 2022 at 18:14
  • @PeterMortensen: (thanks for the syntax highlighting and English fixes, but something seems to be broken now, it says community wiki with you as author?) yes, legacy IP addresses is what IPv4 addresses have been called for a couple of years now, IP addresses are IPv6 addresses.
    – mirabilos
    Feb 14, 2022 at 14:46
3

If you want to improve on a regex that has been working reasonably well over several years, then the answer depends on what exactly you want to achieve - what kinds of email addresses have been failing. Fine-tuning email regexes is very difficult, and I have yet to see a perfect solution.

  • If your application involves something very technical in nature (or something internal to organizations), then maybe you need to support IP addresses instead of domain names, or comments in the "local" part of the email address.
  • If your application is multinational, I would consider focusing on Unicode and UTF-8 support.

The leading answer to your question currently links to a "fully RFC‑822–compliant regex". However, in spite of the complexity of that regex and its presumed attention to detail in RFC rules, it completely fails when it comes to Unicode support.

The regex that I've written for most of my applications focuses on Unicode support, as well as reasonably good overall adherence to RFC standards:

/^(?!\.)((?!.*\.{2})[a-zA-Z0-9\u0080-\u00FF\u0100-\u017F\u0180-\u024F\u0250-\u02AF\u0300-\u036F\u0370-\u03FF\u0400-\u04FF\u0500-\u052F\u0530-\u058F\u0590-\u05FF\u0600-\u06FF\u0700-\u074F\u0750-\u077F\u0780-\u07BF\u07C0-\u07FF\u0900-\u097F\u0980-\u09FF\u0A00-\u0A7F\u0A80-\u0AFF\u0B00-\u0B7F\u0B80-\u0BFF\u0C00-\u0C7F\u0C80-\u0CFF\u0D00-\u0D7F\u0D80-\u0DFF\u0E00-\u0E7F\u0E80-\u0EFF\u0F00-\u0FFF\u1000-\u109F\u10A0-\u10FF\u1100-\u11FF\u1200-\u137F\u1380-\u139F\u13A0-\u13FF\u1400-\u167F\u1680-\u169F\u16A0-\u16FF\u1700-\u171F\u1720-\u173F\u1740-\u175F\u1760-\u177F\u1780-\u17FF\u1800-\u18AF\u1900-\u194F\u1950-\u197F\u1980-\u19DF\u19E0-\u19FF\u1A00-\u1A1F\u1B00-\u1B7F\u1D00-\u1D7F\u1D80-\u1DBF\u1DC0-\u1DFF\u1E00-\u1EFF\u1F00-\u1FFFu20D0-\u20FF\u2100-\u214F\u2C00-\u2C5F\u2C60-\u2C7F\u2C80-\u2CFF\u2D00-\u2D2F\u2D30-\u2D7F\u2D80-\u2DDF\u2F00-\u2FDF\u2FF0-\u2FFF\u3040-\u309F\u30A0-\u30FF\u3100-\u312F\u3130-\u318F\u3190-\u319F\u31C0-\u31EF\u31F0-\u31FF\u3200-\u32FF\u3300-\u33FF\u3400-\u4DBF\u4DC0-\u4DFF\u4E00-\u9FFF\uA000-\uA48F\uA490-\uA4CF\uA700-\uA71F\uA800-\uA82F\uA840-\uA87F\uAC00-\uD7AF\uF900-\uFAFF\.!#$%&'*+-/=?^_`{|}~\-\d]+)@(?!\.)([a-zA-Z0-9\u0080-\u00FF\u0100-\u017F\u0180-\u024F\u0250-\u02AF\u0300-\u036F\u0370-\u03FF\u0400-\u04FF\u0500-\u052F\u0530-\u058F\u0590-\u05FF\u0600-\u06FF\u0700-\u074F\u0750-\u077F\u0780-\u07BF\u07C0-\u07FF\u0900-\u097F\u0980-\u09FF\u0A00-\u0A7F\u0A80-\u0AFF\u0B00-\u0B7F\u0B80-\u0BFF\u0C00-\u0C7F\u0C80-\u0CFF\u0D00-\u0D7F\u0D80-\u0DFF\u0E00-\u0E7F\u0E80-\u0EFF\u0F00-\u0FFF\u1000-\u109F\u10A0-\u10FF\u1100-\u11FF\u1200-\u137F\u1380-\u139F\u13A0-\u13FF\u1400-\u167F\u1680-\u169F\u16A0-\u16FF\u1700-\u171F\u1720-\u173F\u1740-\u175F\u1760-\u177F\u1780-\u17FF\u1800-\u18AF\u1900-\u194F\u1950-\u197F\u1980-\u19DF\u19E0-\u19FF\u1A00-\u1A1F\u1B00-\u1B7F\u1D00-\u1D7F\u1D80-\u1DBF\u1DC0-\u1DFF\u1E00-\u1EFF\u1F00-\u1FFF\u20D0-\u20FF\u2100-\u214F\u2C00-\u2C5F\u2C60-\u2C7F\u2C80-\u2CFF\u2D00-\u2D2F\u2D30-\u2D7F\u2D80-\u2DDF\u2F00-\u2FDF\u2FF0-\u2FFF\u3040-\u309F\u30A0-\u30FF\u3100-\u312F\u3130-\u318F\u3190-\u319F\u31C0-\u31EF\u31F0-\u31FF\u3200-\u32FF\u3300-\u33FF\u3400-\u4DBF\u4DC0-\u4DFF\u4E00-\u9FFF\uA000-\uA48F\uA490-\uA4CF\uA700-\uA71F\uA800-\uA82F\uA840-\uA87F\uAC00-\uD7AF\uF900-\uFAFF\-\.\d]+)((\.([a-zA-Z\u0080-\u00FF\u0100-\u017F\u0180-\u024F\u0250-\u02AF\u0300-\u036F\u0370-\u03FF\u0400-\u04FF\u0500-\u052F\u0530-\u058F\u0590-\u05FF\u0600-\u06FF\u0700-\u074F\u0750-\u077F\u0780-\u07BF\u07C0-\u07FF\u0900-\u097F\u0980-\u09FF\u0A00-\u0A7F\u0A80-\u0AFF\u0B00-\u0B7F\u0B80-\u0BFF\u0C00-\u0C7F\u0C80-\u0CFF\u0D00-\u0D7F\u0D80-\u0DFF\u0E00-\u0E7F\u0E80-\u0EFF\u0F00-\u0FFF\u1000-\u109F\u10A0-\u10FF\u1100-\u11FF\u1200-\u137F\u1380-\u139F\u13A0-\u13FF\u1400-\u167F\u1680-\u169F\u16A0-\u16FF\u1700-\u171F\u1720-\u173F\u1740-\u175F\u1760-\u177F\u1780-\u17FF\u1800-\u18AF\u1900-\u194F\u1950-\u197F\u1980-\u19DF\u19E0-\u19FF\u1A00-\u1A1F\u1B00-\u1B7F\u1D00-\u1D7F\u1D80-\u1DBF\u1DC0-\u1DFF\u1E00-\u1EFF\u1F00-\u1FFF\u20D0-\u20FF\u2100-\u214F\u2C00-\u2C5F\u2C60-\u2C7F\u2C80-\u2CFF\u2D00-\u2D2F\u2D30-\u2D7F\u2D80-\u2DDF\u2F00-\u2FDF\u2FF0-\u2FFF\u3040-\u309F\u30A0-\u30FF\u3100-\u312F\u3130-\u318F\u3190-\u319F\u31C0-\u31EF\u31F0-\u31FF\u3200-\u32FF\u3300-\u33FF\u3400-\u4DBF\u4DC0-\u4DFF\u4E00-\u9FFF\uA000-\uA48F\uA490-\uA4CF\uA700-\uA71F\uA800-\uA82F\uA840-\uA87F\uAC00-\uD7AF\uF900-\uFAFF]){2,63})+)$/i

I'll avoid copy-pasting complete answers, so I'll just link this to a similar answer I provided here: How to validate a unicode email?

There is also a live demo available for the regex above at: http://jsfiddle.net/aossikine/qCLVH/3/

3

The regular expressions posted for this question are out of date now, because of the new generic top-level domains (gTLDs) coming in (e.g. .london, .basketball, .通販). To validate an email address there are two answers (that would be relevant to the vast majority).

  1. As the main answer says - don't use a regular expression. Just validate it by sending an email to the address (catch exceptions for invalid addresses)
  2. Use a very generic regex to at least make sure that they are using an email structure like {something}@{something}.{something}. There's no point in going for a detailed regex, because you won't catch them all and there'll be a new batch in a few years and you'll have to update your regular expression again.

I have decided to use the regular expression because, unfortunately, some users don't read forms and put the wrong data in the wrong fields. This will at least alert them when they try to put something which isn't an email into the email input field and should save you some time supporting users on email issues.

(.+)@(.+){2,}\.(.+){2,}
2
  • What is the difference between a gTLD and a TLD? Feb 14, 2022 at 21:59
  • They're all the same really, but just categorised differently. There are mainly Country Code TLDS (ccTLD), like .co.uk or .fr. These are assigned to each country and contribute as a factor for search engines understand the location/target audience. Sponsored TLDS (sTLD) are assigned to organisations or governments, e.g. .gov The generics (gTLD) cover the extensions which are generic, e.g. .com, .london, .mail, etc. There are some restrictions on which ones you can use, prices can be very different, but Google also says it doesn't matter too much whether you're on a .com or a .whatever.
    – McGaz
    Feb 16, 2022 at 11:26
3

Following is the regular expression for validating an email address:

^.+@\w+(\.\w+)+$
1
  • Given all the previous answers, such a simple regular expression requires an explanation (e.g., why weren't the huge complexity in the previous answers necessary?). What are its properties? What does it fail for? What are some examples that it does work for? What are some examples that it doesn't work for? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today). Feb 14, 2022 at 22:55
3

If you need a simple form to validate, you can use the answer of https://regexr.com/3e48o

^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$

let r = new RegExp(String.raw `^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$`);

//should be true
console.log(r.test('name@domain.tld'));
console.log(r.test('name@domain.co.tld'));
console.log(r.test('name@domain.co'));

//should be false
console.log(r.test('@domain.tld'));
console.log(r.test('name@.tld'));
console.log(r.test('name@domain.'));
console.log(r.test('namedomain.tld'));
console.log(r.test(''));

//now that basic client-side validation is done, send a token from the server side to validate the user actually has access to the email

2
  • 6
    This regex is too simple and rejects ordinary valid emails. It incorrectly rejects the plus particle in the local part (foo+bar@example.com) and incorrectly rejects generic top-level domains with more than four letters (foo@example.dance). Apr 15, 2021 at 13:50
  • This fails over validating .academy domains, for example
    – Pavindu
    Apr 23, 2022 at 12:55
2

A regex that does exactly what the standards say is allowed, according to what I've seen about them, is this:

/^(?!(^[.-].*|.*[.-]@|.*\.{2,}.*)|^.{254}.+@)([a-z\xC0-\xFF0-9!#$%&'*+\/=?^_`{|}~.-]+@)(?!.{253}.+$)((?!-.*|.*-\.)([a-z0-9-]{1,63}\.)+[a-z]{2,63}|(([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])\.){3}([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9]))$/gim

Demo / Debuggex analysis (interactive)

Split up:

^(?!(^[.-].*|.*[.-]@|.*\.{2,}.*)|^.{254}.+@)
([a-z\xC0-\xFF0-9!#$%&'*+\/=?^_`{|}~.-]+@)
(?!.{253}.+$)
(
    (?!-.*|.*-\.)
    ([a-z0-9-]{1,63}\.)+
    [a-z]{2,63}
    |
    (([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])\.){3}
    ([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])
)$

Analysis:

(?!(^[.-].*|.*[.-]@|.*\.{2,}.*)|^.{254}.+@)

Negative lookahead for either an address starting with a ., ending with one, having .. in it, or exceeding the 254 character max length


([a-z\xC0-\xFF0-9!#$%&'*+\/=?^_`{|}~.-]+@)

matching 1 or more of the permitted characters, with the negative look applying to it


(?!.{253}.+$)

Negative lookahead for the domain name part, restricting it to 253 characters in total


(?!-.*|.*-\.)

Negative lookahead for each of the domain names, which are don't allow starting or ending with .


([a-z0-9-]{1,63}\.)+

simple group match for the allowed characters in a domain name, which are limited to 63 characters each


[a-zA-Z]{2,63}

simple group match for the allowed top-level domain, which currently still is restricted to letters only, but does include >4 letter TLDs.


(([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])\.){3}
([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])

the alternative for domain names: this matches the first 3 numbers in an IP address with a . behind it, and then the fourth number in the IP address without . behind it.

1
2

As per my understanding, it will most probably be covered by...

/^([a-z0-9_-]+)(@[a-z0-9-]+)(\.[a-z]+|\.[a-z]+\.[a-z]+)?$/is
3
  • improvement/suggestion always act as catalyst so pls be catalyzed and catalyzed me also. Dec 31, 2012 at 13:11
  • Gmail users often use . and + in their email nick, and some comments on this page mention ' and !. Jan 18, 2013 at 14:42
  • 1
    This is too restrictive, and does not permit numbers in domain names, characters in the user part. o'hare@example.com, me+alpha@example.com, and me@mail.s2.example.com are all valid email addresses that this does not validate.
    – awwright
    Sep 15, 2020 at 2:48
2

I found a regular expression that is compliant with RFC 2822. The preceding standard to RFC 5322. This regular expression appears to perform fairly well and will cover most cases, however with RFC 5322 becoming the standard there may be some holes that ought to be plugged.

^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$

The documentation says you shouldn't use the above regular expression, but instead favour this flavour, which is a bit more manageable.

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

I noticed this is case-sensitive, so I actually made an alteration to this landing.

^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$
2

There has nearly been added a new domain, "yandex". Possible emails: test@job.yandex. And also uppercase letters are supported, so a bit modified version of acrosman's solution is:

^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,6})$
2
  • 2
    This is too restrictive, and disallows valid email addresses like o'hare@example.com
    – awwright
    Sep 12, 2020 at 23:43
  • Re "acrosman's solution": User acrosman has not posted a solution or answer, only a question. What answer does this refer to? Feb 14, 2022 at 21:46
2

Java Mail API does magic for us.

try
{
    InternetAddress internetAddress = new InternetAddress(email);
    internetAddress.validate();
    return true;
}
catch(Exception ex)
{
    return false;
}

I got this from here.

1
  • 1
    Java Mail API is an optional package for use with Java SE platform and is included in the Java EE platform. Dec 11, 2014 at 7:56
2

List item

I use this function

function checkmail($value) {
    $value = trim($value);
    if (stristr($value,"@") &&
        stristr($value,".") &&
        (strrpos($value, ".") - stripos($value, "@") > 2) &&
        (stripos($value, "@") > 1) &&
        (strlen($value) - strrpos($value, ".") < 6) &&
        (strlen($value) - strrpos($value, ".") > 2) &&
        ($value == preg_replace('/[ ]/', '', $value)) &&
        ($value == preg_replace('/[^A-Za-z0-9\-_.@!*]/', '', $value))
    )
    {

    }
    else {
        return "Invalid Mail-Id";
    }
}
2

Writing a regular expression for all the things will take a lot of effort. Instead, you can use pyIsEmail package.

Below text is taken from pyIsEmail website.

pyIsEmail is a no-nonsense approach for checking whether that user-supplied email address could be real.

Regular expressions are cheap to write, but often require maintenance when new top-level domains come out or don’t conform to email addressing features that come back into vogue. pyIsEmail allows you to validate an email address – and even check the domain, if you wish – with one simple call, making your code more readable and faster to write. When you want to know why an email address doesn’t validate, they even provide you with a diagnosis.

Usage

For the simplest usage, import and use the is_email function:

from pyisemail import is_email

address = "test@example.com"
bool_result = is_email(address)
detailed_result = is_email(address, diagnose=True)

You can also check whether the domain used in the email is a valid domain and whether or not it has a valid MX record:

from pyisemail import is_email

address = "test@example.com"
bool_result_with_dns = is_email(address, check_dns=True)
detailed_result_with_dns = is_email(address, check_dns=True, diagnose=True)

These are primary indicators of whether an email address can even be issued at that domain. However, a valid response here is not a guarantee that the email exists, merely that is can exist.

In addition to the base is_email functionality, you can also use the validators by themselves. Check the validator source doc to see how this works.

2
  • Re "...when new top-level domains come out": Aren't there literally thousands by now? Feb 15, 2022 at 0:00
  • This sounds more like an advert. What does it actually do? What is the gist? Does it go live over the Internet to do some lookups or checks (that involves some DNS stuff)? Effectively trying to send the email to see what happens? Or something else? Feb 15, 2022 at 0:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.