Regex Email validation

2018-12-31 16:25发布

I use this

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

regexp to validate the email

([\w\.\-]+) - this is for the first-level domain (many letters and numbers, also point and hyphen)

([\w\-]+) - this is for second-level domain

((\.(\w){2,3})+) - and this is for other level domains(from 3 to infinity) which includes a point and 2 or 3 literals

what's wrong with this regex?

EDIT:it doesn't match the "something@someth.ing" email

30条回答
余生无你
2楼-- · 2018-12-31 16:58

The following code is based on Microsoft's Data annotations implementation on github and I think it's the most complete validation for emails:

public static Regex EmailValidation()
{
    const string pattern = @"^((([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])))\.?$";
    const RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture;

    // Set explicit regex match timeout, sufficient enough for email parsing
    // Unless the global REGEX_DEFAULT_MATCH_TIMEOUT is already set
    TimeSpan matchTimeout = TimeSpan.FromSeconds(2);

    try
    {
        if (AppDomain.CurrentDomain.GetData("REGEX_DEFAULT_MATCH_TIMEOUT") == null)
        {
            return new Regex(pattern, options, matchTimeout);
        }
    }
    catch
    {
        // Fallback on error
    }

    // Legacy fallback (without explicit match timeout)
    return new Regex(pattern, options);
}
查看更多
永恒的永恒
3楼-- · 2018-12-31 16:59

I think your caret and dollar sign are part of the problem You should also modify the regex a little, I use the next @"[ :]+([\w.-]+)@([\w-.])+((.(\w){2,3})+)"

查看更多
无与为乐者.
4楼-- · 2018-12-31 16:59
public bool checkEmailAddress(string emailAddress)
{
    // FullKade.COm
    string patternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
        + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
        + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
        + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
        +    @"[a-zA-Z]{2,}))$";
    Regex reStrict = new Regex(patternStrict);
    bool isStrictMatch = reStrict.IsMatch(emailAddress);
    return isStrictMatch;
    // FullKade.COm
}
查看更多
几人难应
5楼-- · 2018-12-31 17:00

Try the Following Code:

using System.Text.RegularExpressions;
if  (!Regex.IsMatch(txtEmail.Text, @"^[a-z,A-Z]{1,10}((-|.)\w+)*@\w+.\w{3}$"))
        MessageBox.Show("Not valid email.");
查看更多
冷夜・残月
6楼-- · 2018-12-31 17:01

I found nice document on MSDN for it.

How to: Verify that Strings Are in Valid Email Format http://msdn.microsoft.com/en-us/library/01escwtf.aspx (check out that this code also supports the use of non-ASCII characters for Internet domain names.)

There are 2 implementation, for .Net 2.0/3.0 and for .Net 3.5 and higher.
the 2.0/3.0 version is:

bool IsValidEmail(string strIn)
{
    // Return true if strIn is in valid e-mail format.
    return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); 
}

My tests over this method give:

Invalid: @majjf.com
Invalid: A@b@c@example.com
Invalid: Abc.example.com
Valid: j..s@proseware.com
Valid: j.@server1.proseware.com
Invalid: js*@proseware.com
Invalid: js@proseware..com
Valid: ma...ma@jjf.co
Valid: ma.@jjf.com
Invalid: ma@@jjf.com
Invalid: ma@jjf.
Invalid: ma@jjf..com
Invalid: ma@jjf.c
Invalid: ma_@jjf
Invalid: ma_@jjf.
Valid: ma_@jjf.com
Invalid: -------
Valid: 12@hostname.com
Valid: d.j@server1.proseware.com
Valid: david.jones@proseware.com
Valid: j.s@server1.proseware.com
Invalid: j@proseware.com9
Valid: j_9@[129.126.118.1]
Valid: jones@ms1.proseware.com
Invalid: js#internal@proseware.com
Invalid: js@proseware.com9
Invalid: js@proseware.com9
Valid: m.a@hostname.co
Valid: m_a1a@hostname.com
Valid: ma.h.saraf.onemore@hostname.com.edu
Valid: ma@hostname.com
Invalid: ma@hostname.comcom
Invalid: MA@hostname.coMCom
Valid: ma12@hostname.com
Valid: ma-a.aa@hostname.com.edu
Valid: ma-a@hostname.com
Valid: ma-a@hostname.com.edu
Valid: ma-a@1hostname.com
Valid: ma.a@1hostname.com
Valid: ma@1hostname.com
查看更多
流年柔荑漫光年
7楼-- · 2018-12-31 17:01

This is my favorite approach to this so far:

public static class CommonExtensions
{
    public static bool IsValidEmail(this string thisEmail)
        => !string.IsNullOrWhiteSpace(thisEmail) &&
           new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$").IsMatch(thisEmail);
}

Then use the created string extension like:

if (!emailAsString.IsValidEmail()) throw new Exception("Invalid Email");
查看更多
登录 后发表回答