正则表达式有效的电子邮件检查

Regexp valid email check

我尝试使用以下正则表达式检查电子邮件是否有效。

/[0-9A-Za-z-_.]{1,64}[\@][0-9a-zA-Z\-]{1,63}[\.][a-zA-Z\-]{2,24}/

但在测试中我看到像 test---@gmail.comtest-.-@gmail.comtest-.@gmail.comtest.@gmail.comtest__@gmail.com__--.test@gmail.com 这样的无效电子邮件是标记为有效。

我认为没有有效的电子邮件是。 , _ , - 在开头或结尾,而不是像 -- 或 __ 或 - 一样在彼此后面。或 .- ...

我可以做些什么来让它变得更好?

为什么不用http://php.net/manual/en/function.filter-var.php

if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  echo("$email is a valid email address");
} else {
  echo("$email is not a valid email address");
}

在此处查看过滤器定义。 http://php.net/manual/en/filter.filters.validate.php

Validates whether the value is a valid e-mail address.

In general, this validates e-mail addresses against the syntax in RFC 822, with the exceptions that comments and whitespace folding and dotless domain names are not supported.

试试这个:

^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})$

另一种方式:

^(|(([A-Za-z0-9]+)|([A-Za-z0-9]+)|([A-Za-z0-9]+(\.[_a-z0-9-]+)+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})$

不匹配:

test-.@gmail.com
test.@gmail.com
test__@gmail.com
__--.test@gmail.com
john__doe@gmail.com
john..doe@xuse.de
john--doe@xuse.de
test_test@gmail.com

匹配:

12test21@gmail.com
1.test@gmail.com
test.test@gmail.com