Regular expression for email

Possible Duplicate:
What is the best regular expression for validating email addresses?

I am using this particular regular expression for checking emails.

"^[A-Za-z0-9](([a-zA-Z0-9,=.!-#|$%^&*+/?_`{}~]+)*)@(?:[0-9a-zA-Z-]+.)+[a-zA-Z]{2,9}$"

The issue I have is that, this allows periods before the "@" symbol. Is there any way this expression be modified so that this does not happen, yet all other conditions are maintained.

a.@b.com should be invalid

Thanks in advance -Rollin


you could put [^.] before the @ so that it will allow any character except the dot

of course this is probably not what you want, so you could just put a [] with any legal characters in it

just in case someone has a email name (i mean the part before the @ ) that is just 1 character, you might need to get creative with the |


The best answer I've seen so far. Honestly, if you gave some indication of which language or toolset you were using, I would point you to the library that does it for you rather than telling you how to hand-roll a regular expression for this.

Edit: Given the additional information that this is on .NET, I would use the MailAddress class and abandon the thought of using regular expressions altogether like so:

public bool IsAddressValid(string text)
{
    try
    {
        MailAddress address = new MailAddress(text);
        return true;
    }
    catch (FormatException)
    {
        return false;
    }
}

If there are additional requirements over and above validating the address itself (like making sure it is from a particular set of domains or some such) then you can do that with much simpler tests after you have verified that the address is valid as I suggested in another post.


A strange game. The only winning move is not to play.

Seriously, the only winning way to validate email addresses with a regular expression is to not validate email addresses with a regular expression. The grammar that accepts email addresses is not regular. It's true that modern regular expressions can support some non-regular grammars, but even so, maintaining a regular expression for such a complex grammar is (as you can see) nearly impossible.

The only reasonable use of regular expressions with email addresses that I can think of is to do some minimal checking on the client side (does it contain an @ symbol?).

What you should do is:

  • Send an email to the email address with a link for the user to click. If the user clicks the link, the email address is valid. Furthermore, it exists, and the user is probably the one who entered the email address into your form. Not only does this 100% validate the email address, it gives you even more guarantees.

  • If you can't do 1, use a prepackaged email validator. Better, use both 1 and 2.

  • If you can't do 1 or 2, write a real parser to validate email addresses.

  • 链接地址: http://www.djcxy.com/p/16574.html

    上一篇: 电子邮件正则表达式

    下一篇: 电子邮件正则表达式