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:53
string patternEmail = @"(?<email>\w+@\w+\.[a-z]{0,3})";
Regex regexEmail = new Regex(patternEmail);
查看更多
千与千寻千般痛.
3楼-- · 2018-12-31 16:53

It has taken many attempts to create an email validator which catches nearly all worldwide requirements for email.

Extension method you can call with:

myEmailString.IsValidEmailAddress();

Regex pattern string you can get by calling:

var myPattern = Regex.EmailPattern;

The Code (mostly comments):

    /// <summary>
    /// Validates the string is an Email Address...
    /// </summary>
    /// <param name="emailAddress"></param>
    /// <returns>bool</returns>
    public static bool IsValidEmailAddress(this string emailAddress)
    {
        var valid = true;
        var isnotblank = false;

        var email = emailAddress.Trim();
        if (email.Length > 0)
        {
            // Email Address Cannot start with period.
            // Name portion must be at least one character
            // In the Name, valid characters are:  a-z 0-9 ! # _ % & ' " = ` { } ~ - + * ? ^ | / $
            // Cannot have period immediately before @ sign.
            // Cannot have two @ symbols
            // In the domain, valid characters are: a-z 0-9 - .
            // Domain cannot start with a period or dash
            // Domain name must be 2 characters.. not more than 256 characters
            // Domain cannot end with a period or dash.
            // Domain must contain a period
            isnotblank = true;
            valid = Regex.IsMatch(email, Regex.EmailPattern, RegexOptions.IgnoreCase) &&
                !email.StartsWith("-") &&
                !email.StartsWith(".") &&
                !email.EndsWith(".") && 
                !email.Contains("..") &&
                !email.Contains(".@") &&
                !email.Contains("@.");
        }

        return (valid && isnotblank);
    }

    /// <summary>
    /// Validates the string is an Email Address or a delimited string of email addresses...
    /// </summary>
    /// <param name="emailAddress"></param>
    /// <returns>bool</returns>
    public static bool IsValidEmailAddressDelimitedList(this string emailAddress, char delimiter = ';')
    {
        var valid = true;
        var isnotblank = false;

        string[] emails = emailAddress.Split(delimiter);

        foreach (string e in emails)
        {
            var email = e.Trim();
            if (email.Length > 0 && valid) // if valid == false, no reason to continue checking
            {
                isnotblank = true;
                if (!email.IsValidEmailAddress())
                {
                    valid = false;
                }
            }
        }
        return (valid && isnotblank);
    }

    public class Regex
    {
        /// <summary>
        /// Set of Unicode Characters currently supported in the application for email, etc.
        /// </summary>
        public static readonly string UnicodeCharacters = "À-ÿ\p{L}\p{M}ÀàÂâÆæÇçÈèÉéÊêËëÎîÏïÔôŒœÙùÛûÜü«»€₣äÄöÖüÜß"; // German and French

        /// <summary>
        /// Set of Symbol Characters currently supported in the application for email, etc.
        /// Needed if a client side validator is being used.
        /// Not needed if validation is done server side.
        /// The difference is due to subtle differences in Regex engines.
        /// </summary>
        public static readonly string SymbolCharacters = @"!#%&'""=`{}~\.\-\+\*\?\^\|\/\$";

        /// <summary>
        /// Regular Expression string pattern used to match an email address.
        /// The following characters will be supported anywhere in the email address:
        /// ÀàÂâÆæÇçÈèÉéÊêËëÎîÏïÔôŒœÙùÛûÜü«»€₣äÄöÖüÜß[a - z][A - Z][0 - 9] _
        /// The following symbols will be supported in the first part of the email address(before the @ symbol):
        /// !#%&'"=`{}~.-+*?^|\/$
        /// Emails cannot start or end with periods,dashes or @.
        /// Emails cannot have two @ symbols.
        /// Emails must have an @ symbol followed later by a period.
        /// Emails cannot have a period before or after the @ symbol.
        /// </summary>
        public static readonly string EmailPattern = String.Format(
            @"^([\w{0}{2}])+@{1}[\w{0}]+([-.][\w{0}]+)*\.[\w{0}]+([-.][\w{0}]+)*$",                     //  @"^[{0}\w]+([-+.'][{0}\w]+)*@[{0}\w]+([-.][{0}\w]+)*\.[{0}\w]+([-.][{0}\w]+)*$",
            UnicodeCharacters,
            "{1}",
            SymbolCharacters
        );
    }
查看更多
查无此人
4楼-- · 2018-12-31 16:54

This does not meet all of the requirements of RFCs 5321 and 5322, but it works with the following definitions.

@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";

Below is the code

const String pattern =
   @"^([0-9a-zA-Z]" + //Start with a digit or alphabetical
   @"([\+\-_\.][0-9a-zA-Z]+)*" + // No continuous or ending +-_. chars in email
   @")+" +
   @"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";

var validEmails = new[] {
        "ma@hostname.com",
        "ma@hostname.comcom",
        "MA@hostname.coMCom",
        "m.a@hostname.co",
        "m_a1a@hostname.com",
        "ma-a@hostname.com",
        "ma-a@hostname.com.edu",
        "ma-a.aa@hostname.com.edu",
        "ma.h.saraf.onemore@hostname.com.edu",
        "ma12@hostname.com",
        "12@hostname.com",
};
var invalidEmails = new[] {
        "Abc.example.com",     // No `@`
        "A@b@c@example.com",   // multiple `@`
        "ma...ma@jjf.co",      // continuous multiple dots in name
        "ma@jjf.c",            // only 1 char in extension
        "ma@jjf..com",         // continuous multiple dots in domain
        "ma@@jjf.com",         // continuous multiple `@`
        "@majjf.com",          // nothing before `@`
        "ma.@jjf.com",         // nothing after `.`
        "ma_@jjf.com",         // nothing after `_`
        "ma_@jjf",             // no domain extension 
        "ma_@jjf.",            // nothing after `_` and .
        "ma@jjf.",             // nothing after `.`
    };

foreach (var str in validEmails)
{
    Console.WriteLine("{0} - {1} ", str, Regex.IsMatch(str, pattern));
}
foreach (var str in invalidEmails)
{
    Console.WriteLine("{0} - {1} ", str, Regex.IsMatch(str, pattern));
}
查看更多
几人难应
5楼-- · 2018-12-31 16:54
public static bool ValidateEmail(string str)
{                       
     return Regex.IsMatch(str, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
}

I use the above code to validate the email address.

查看更多
君临天下
6楼-- · 2018-12-31 16:54

I've been using the Regex.IsMatch().

First of all you need to add the next statement:

using System.Text.RegularExpressions;

Then the method looks like:

private bool EmailValidation(string pEmail)
{
                 return Regex.IsMatch(pEmail,
                 @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                 RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
}

It's a private method because of my logic but you can put the method as static in another Layer such as "Utilities" and call it from where you need.

查看更多
裙下三千臣
7楼-- · 2018-12-31 16:54

Visual studio had this for years.

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

Hope this helps!

查看更多
登录 后发表回答