我用这个
@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
Regexp来验证电子邮件
([\w\.\-]+) -用于第一级域名(许多字母和数字,也有点和连字符) ([\w\-]+) -用于二级域 ((\.(\w){2,3})+) -这是用于其他级别域(从3到无穷),其中包括一个点和2或3个字面量
这个正则表达式有什么问题?
编辑:它与“something@someth.ing”电子邮件不匹配
我用这个
@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
Regexp来验证电子邮件
([\w\.\-]+) -用于第一级域名(许多字母和数字,也有点和连字符) ([\w\-]+) -用于二级域 ((\.(\w){2,3})+) -这是用于其他级别域(从3到无穷),其中包括一个点和2或3个字面量
这个正则表达式有什么问题?
编辑:它与“something@someth.ing”电子邮件不匹配
当前回答
这可以防止其他人在评论中提到的无效邮件:
Abc.@example.com
Abc..123@example.com
name@hotmail
toms.email.@gmail.com
test@-online.com
它还可以防止带有双点的电子邮件:
hello..world@example..com
试着用尽可能多的无效电子邮件地址进行测试。
using System.Text.RegularExpressions;
public static bool IsValidEmail(string email)
{
return Regex.IsMatch(email, @"\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}\z")
&& Regex.IsMatch(email, @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*");
}
请参阅在c#中使用正则表达式验证电子邮件地址。
其他回答
它采取了许多尝试,以创建一个电子邮件验证器,捕捉几乎所有的全球电子邮件需求。
扩展方法,你可以调用:
myEmailString.IsValidEmailAddress();
正则表达式模式字符串,你可以通过调用:
var myPattern = Regex.EmailPattern;
准则(主要是评论):
/// <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
);
}
我一直在使用regx . ismatch()。
首先,你需要添加下一个语句:
using System.Text.RegularExpressions;
然后该方法如下所示:
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));
}
这是一个私有方法,因为我的逻辑,但你可以把方法作为静态放在另一个层,如“实用工具”,并从你需要的地方调用它。
这段代码将有助于在c#.Net中使用正则表达式验证电子邮件id。它很容易使用
if (!System.Text.RegularExpressions.Regex.IsMatch("<Email String Here>", @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"))
{
MessageBox.show("Incorrect Email Id.");
}
如果它不起作用,请告诉我:)
public static bool isValidEmail(this string email)
{
string[] mail = email.Split(new string[] { "@" }, StringSplitOptions.None);
if (mail.Length != 2)
return false;
//check part before ...@
if (mail[0].Length < 1)
return false;
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_\-\.]+$");
if (!regex.IsMatch(mail[0]))
return false;
//check part after @...
string[] domain = mail[1].Split(new string[] { "." }, StringSplitOptions.None);
if (domain.Length < 2)
return false;
regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_\-]+$");
foreach (string d in domain)
{
if (!regex.IsMatch(d))
return false;
}
//get TLD
if (domain[domain.Length - 1].Length < 2)
return false;
return true;
}
像。museum这样的顶级域名就不是这样匹配的,还有一些其他的长顶级域名。此外,你可以使用MailAddress类验证电子邮件地址,微软在这里解释了一个说明:
与使用正则表达式验证电子邮件地址不同, 你可以使用System.Net.Mail.MailAddress类。来确定 电子邮件地址是否有效,将电子邮件地址传递给 mailaddress (String)类构造函数。
public bool IsValid(string emailaddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
这为您省去了很多麻烦,因为您不必编写(或试图理解他人的)正则表达式。
编辑:对于那些对尝试/捕捉过敏的人:在。net 5中,你可以使用MailAddress.TryCreate。请参见https://stackoverflow.com/a/68198658,包括如何修复的示例。,空格,缺失。tld等。