Ser*_*gey 206 c# regex validation
我用这个
@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
Run Code Online (Sandbox Code Playgroud)
regexp验证电子邮件
([\w\.\-]+)
- 这是针对第一级域名(许多字母和数字,也是点和连字符)
([\w\-]+)
- 这是针对二级域名
((\.(\w){2,3})+)
- 这适用于其他级别域名(从3到无穷大),包括一个点和2或3文字
这个正则表达式有什么问题?
编辑:它与"something@someth.ing"电子邮件不符
Ale*_*lex 347
TLD就像.museum这种方式不匹配,还有一些其他长TLD.此外,您可以使用MailAddress类验证电子邮件地址,正如Microsoft 在此处的说明中所述:
您可以使用System.Net.Mail.MailAddress类,而不是使用正则表达式来验证电子邮件地址.要确定电子邮件地址是否有效,请将电子邮件地址传递给MailAddress.MailAddress(String)类构造函数.
public bool IsValid(string emailaddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
这可以为您节省很多麻烦,因为您不必编写(或尝试理解其他人的)正则表达式.
小智 91
我觉得@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
应该有用.
你需要写它
string email = txtemail.Text;
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
Response.Write(email + " is correct");
else
Response.Write(email + " is incorrect");
Run Code Online (Sandbox Code Playgroud)
请注意,如果出现以下情况,则会失败:
@
符号后面有一个子域.
您使用长度大于3的TLD,例如 .info
Rhy*_*ous 67
我有一个表达式来检查我使用的电子邮件地址.
由于以上都不像我的那么短或准确,我想我会在这里发布.
@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*"
+ "@"
+ @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$";
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请在此处阅读:C#中的正则表达式(包括新的综合电子邮件模式)
此外,这将根据电子邮件语法检查RFC有效性,而不是检查电子邮件是否确实存在.测试电子邮件确实存在的唯一方法是发送和发送电子邮件,让用户通过单击链接或输入令牌来验证他们是否收到了电子邮件.
然后有一些丢弃的域名,例如Mailinator.com等.这无法验证电子邮件是否来自一次性域.
mr.*_*123 35
我在MSDN上找到了很好的文档.
如何:验证字符串是否为有效的电子邮件格式 http://msdn.microsoft.com/en-us/library/01escwtf.aspx (请注意此代码还支持对Internet域名使用非ASCII字符. )
对于.Net 2.0/3.0和.Net 3.5及更高版本,有2个实现.
2.0/3.0版本是:
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})(\]?)$");
}
Run Code Online (Sandbox Code Playgroud)
我对这种方法的测试给出了:
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
Run Code Online (Sandbox Code Playgroud)
Mar*_*l W 16
作为Alex的热门答案的更新:在 .NET 5 MailAddress 现在有一个 TryCreate。所以你可以这样做:
public static bool IsValidEmail(string email)
{
if (!MailAddress.TryCreate(email, out var mailAddress))
return false;
// And if you want to be more strict:
var hostParts = mailAddress.Host.Split('.');
if (hostParts.Length == 1)
return false; // No dot.
if (hostParts.Any(p => p == string.Empty))
return false; // Double dot.
if (hostParts[^1].Length < 2)
return false; // TLD only one letter.
if (mailAddress.User.Contains(' '))
return false;
if (mailAddress.User.Split('.').Any(p => p == string.Empty))
return false; // Double dot or dot at end of user part.
return true;
}
Run Code Online (Sandbox Code Playgroud)
Cod*_*ist 12
以下代码基于Microsoft在github上的Data annotations实现,我认为这是对电子邮件最完整的验证:
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);
}
Run Code Online (Sandbox Code Playgroud)
Mah*_*eep 11
这不符合RFC 5321和5322的所有要求,但它适用于以下定义.
@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";
Run Code Online (Sandbox Code Playgroud)
下面是代码
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));
}
Run Code Online (Sandbox Code Playgroud)
小智 7
最佳电子邮件验证正则表达式
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Run Code Online (Sandbox Code Playgroud)
这是用法: -
bool isEmail = Regex.IsMatch(emailString, @"\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", RegexOptions.IgnoreCase);
Run Code Online (Sandbox Code Playgroud)
试试这个尺码:
public static bool IsValidEmailAddress(this string s)
{
var regex = new Regex(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
return regex.IsMatch(s);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
为什么不使用基于 EF6 属性的电子邮件验证?
正如您在上面看到的,电子邮件的正则表达式验证总是有一些漏洞。如果您正在使用 EF6 数据注释,则可以使用可用的EmailAddress数据注释属性轻松实现可靠且更强大的电子邮件验证。当我在电子邮件输入字段上遇到移动设备特定的正则表达式失败时,我不得不删除我之前用于电子邮件的正则表达式验证。当数据注释属性用于电子邮件验证时,解决了移动设备上的问题。
public class LoginViewModel
{
[EmailAddress(ErrorMessage = "The email format is not valid")]
public string Email{ get; set; }
Run Code Online (Sandbox Code Playgroud)
这个正则表达式完美地工作:
bool IsValidEmail(string email)
{
return Regex.IsMatch(email, @"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))\z");
}
Run Code Online (Sandbox Code Playgroud)
new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(input)
Run Code Online (Sandbox Code Playgroud)
试试这个,它对我有用:
public bool IsValidEmailAddress(string s)
{
if (string.IsNullOrEmpty(s))
return false;
else
{
var regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
return regex.IsMatch(s) && !s.EndsWith(".");
}
}
Run Code Online (Sandbox Code Playgroud)
这可以防止其他人在评论中提到的无效电子邮件:
Abc.@example.com
Abc..123@example.com
name@hotmail
toms.email.@gmail.com
test@-online.com
Run Code Online (Sandbox Code Playgroud)
它还可以防止带有双点的电子邮件:
hello..world@example..com
Run Code Online (Sandbox Code Playgroud)
尝试使用尽可能多的无效电子邮件地址进行测试。
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}$).*");
}
Run Code Online (Sandbox Code Playgroud)
使用正则表达式验证电子邮件
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";
//check first string
if (Regex.IsMatch(EmailId1 , pattern))
{
//if email is valid
Console.WriteLine(EmailId1+ " is a valid Email address ");
}
Run Code Online (Sandbox Code Playgroud)
来源:电子邮件验证 C#
使用MailAddress.MailAddress(String)类构造函数在没有正则表达式的情况下进行验证
public bool IsEmailValid(string emailaddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)