现正则表达式
可能重复:
What is the best regular expression for validating email addresses?现正则表达式重复:What is the best regular expression for validating email addresses?
我知道这是一个常见的问题,但我仍然似乎无法找到一个伟大的正则表达式在验证电子邮件地址时使用。
我真的没有时间去阅读规范和写我自己的。你以前使用过什么,并且运行良好?我并不在意100%符合规格,但越接近越好。
下面是我使用的功能。它多一点不仅仅是运行通过正则表达式的电子邮件地址,但到目前为止,它是最完整的解决方案,我发现:
function validEmail($email, $skipDNS = false)
{
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
if(!$skipDNS)
{
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
}
}
return $isValid;
}
函数有可选$ skipDNS参数可以设置为如果您不想验证主机的MX记录,则为TRUE。否则,该功能将尝试验证提供的电子邮件地址实际上是否映射到真实的电子邮件服务器。
请注意,大多数RegEx电子邮件验证技术将验证大多数电子邮件地址,但它们很可能会允许一些精心设计的无效地址或最差..在一些更模糊但有效的电子邮件地址上失败。欲了解更多信息,你可能想看看Internet Message Formats RFC其中描述的电子邮件地址允许的格式。
^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$
这是一个真棒工具,帮助写检查的表情,不知道你是否拥有它,但希望它的帮助。
这个正则表达式是诱发灾难性回溯的一种肯定的方式,正如本[后续问题]所证明的(http: //stackoverflow.com/q/13087755/20670)。 – 2012-10-26 13:34:43
不要使用此 - 请参阅:http://stackoverflow.com/questions/13087755/can-anyone-tell-me-why-this-c-sharp-email-validation-regular-expression-regex – 2012-10-26 13:40:17
有很多关于电子邮件正则表达式的问题。 http://stackoverflow.com/questions/508108/regex-for-email-validation-closed – Macarse 2009-06-15 16:39:28