验证字符串是否是有效的电子邮件地址的最优雅的代码是什么?
当前回答
我将Poyson 1的答案简化如下:
public static bool IsValidEmailAddress(string candidateEmailAddr)
{
string regexExpresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
return (Regex.IsMatch(candidateEmailAddr, regexExpresion)) &&
(Regex.Replace(candidateEmailAddr, regexExpresion, string.Empty).Length == 0);
}
其他回答
老实说,在产品代码中,我所做的最好的事情就是检查@符号。
我从来没有在一个地方完全验证电子邮件。你知道我怎么判断它是否有效吗?如果发送出去了。如果没有,那就糟了,如果有,生活就好了。这就是我需要知道的。
这是你问题的答案,供你核对。
using System;
using System.Globalization;
using System.Text.RegularExpressions;
public class RegexUtilities
{
public bool IsValidEmail(string strIn)
{
if (String.IsNullOrEmpty(strIn))
{
return false;
}
// Use IdnMapping class to convert Unicode domain names.
try
{
strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds(200));
}
catch (RegexMatchTimeoutException)
{
return false;
}
if (invalid)
{
return false;
}
// Return true if strIn is in valid e-mail format.
try
{
return Regex.IsMatch(strIn, @"^(?("")("".+?(?<!\\)""@)|(([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));
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
private string DomainMapper(Match match)
{
// IdnMapping class with default property values.
IdnMapping idn = new IdnMapping();
string domainName = match.Groups[2].Value;
try
{
domainName = idn.GetAscii(domainName);
}
catch (ArgumentException)
{
invalid = true;
}
return match.Groups[1].Value + domainName;
}
}
我写了一个函数来检查电子邮件是否有效。在大多数情况下,这似乎对我很有效。
结果:
dasddas-@.com => FALSE
-asd@das.com => FALSE
as3d@dac.coas- => FALSE
dsq!a?@das.com => FALSE
_dasd@sd.com => FALSE
dad@sds => FALSE
asd-@asd.com => FALSE
dasd_-@jdas.com => FALSE
asd@dasd@asd.cm => FALSE
da23@das..com => FALSE
_dasd_das_@9.com => FALSE
d23d@da9.co9 => TRUE
dasd.dadas@dasd.com => TRUE
dda_das@das-dasd.com => TRUE
dasd-dasd@das.com.das => TRUE
代码:
private bool IsValidEmail(string email)
{
bool valid = false;
try
{
var addr = new System.Net.Mail.MailAddress(email);
valid = true;
}
catch
{
valid = false;
goto End_Func;
}
valid = false;
int pos_at = email.IndexOf('@');
char checker = Convert.ToChar(email.Substring(pos_at + 1, 1));
var chars = "qwertyuiopasdfghjklzxcvbnm0123456789";
foreach (char chr in chars)
{
if (checker == chr)
{
valid = true;
break;
}
}
if (valid == false)
{
goto End_Func;
}
int pos_dot = email.IndexOf('.', pos_at + 1);
if(pos_dot == -1)
{
valid = false;
goto End_Func;
}
valid = false;
try
{
checker = Convert.ToChar(email.Substring(pos_dot + 1, 1));
foreach (char chr in chars)
{
if (checker == chr)
{
valid = true;
break;
}
}
}
catch
{
valid = false;
goto End_Func;
}
Regex valid_checker = new Regex(@"^[a-zA-Z0-9_@.-]*$");
valid = valid_checker.IsMatch(email);
if (valid == false)
{
goto End_Func;
}
List<int> pos_list = new List<int> { };
int pos = 0;
while (email.IndexOf('_', pos) != -1)
{
pos_list.Add(email.IndexOf('_', pos));
pos = email.IndexOf('_', pos) + 1;
}
pos = 0;
while (email.IndexOf('.', pos) != -1)
{
pos_list.Add(email.IndexOf('.', pos));
pos = email.IndexOf('.', pos) + 1;
}
pos = 0;
while (email.IndexOf('-', pos) != -1)
{
pos_list.Add(email.IndexOf('-', pos));
pos = email.IndexOf('-', pos) + 1;
}
int sp_cnt = pos_list.Count();
pos_list.Sort();
for (int i = 0; i < sp_cnt - 1; i++)
{
if (pos_list[i] + 1 == pos_list[i + 1])
{
valid = false;
break;
}
if (pos_list[i]+1 == pos_at || pos_list[i]+1 == pos_dot)
{
valid = false;
break;
}
}
if(valid == false)
{
goto End_Func;
}
if (pos_list[sp_cnt - 1] == email.Length - 1 || pos_list[0] == 0)
{
valid = false;
}
End_Func:;
return valid;
}
另一个正则表达式匹配答案:
/// <summary>
/// Validates the email input
/// </summary>
internal static bool ValidateEmail(string _emailAddress)
{
string _regexPattern = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
return (string.IsNullOrEmpty(_emailAddress) == false && System.Text.RegularExpressions.Regex.IsMatch(_emailAddress, _regexPattern))
? true
: false;
}
短而准确的代码
string Email = txtEmail.Text;
if (Email.IsValidEmail())
{
//use code here
}
public static bool IsValidEmail(this string email)
{
string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
return regex.IsMatch(email);
}
推荐文章
- 在c#中从URI字符串获取文件名
- 检查SqlDataReader对象中的列名
- 如何将类标记为已弃用?
- c# 8支持。net框架吗?
- Linq-to-Entities Join vs GroupJoin
- 为什么字符串类型的默认值是null而不是空字符串?
- 在list中获取不同值的列表
- 组合框:向项目添加文本和值(无绑定源)
- 如何为ASP.net/C#应用程序配置文件值中的值添加&号
- 从System.Drawing.Bitmap中加载WPF BitmapImage
- 如何找出一个文件存在于c# / .NET?
- 为什么更快地检查字典是否包含键,而不是捕捉异常,以防它不?
- [DataContract]的命名空间
- string. isnullorempty (string) vs. string. isnullowhitespace (string)
- 完全外部连接