编写一个函数或程序,以放松您可以忽略注释并折叠空白()和通用地址文字的方式,根据RFC 5321(在5322中找到一些语法规则)来验证电子邮件地址CFWS
。这给出了语法
Mailbox = Local-part "@" ( Domain / address-literal )
Local-part = Dot-string / Quoted-string
Dot-string = Atom *("." Atom)
Atom = 1*atext
atext = ALPHA / DIGIT / ; Printable US-ASCII
"!" / "#" / ; characters not including
"$" / "%" / ; specials. Used for atoms.
"&" / "'" /
"*" / "+" /
"-" / "/" /
"=" / "?" /
"^" / "_" /
"`" / "{" /
"|" / "}" /
"~"
Quoted-string = DQUOTE *QcontentSMTP DQUOTE
QcontentSMTP = qtextSMTP / quoted-pairSMTP
qtextSMTP = %d32-33 / %d35-91 / %d93-126
quoted-pairSMTP = %d92 %d32-126
Domain = sub-domain *("." sub-domain)
sub-domain = Let-dig [Ldh-str]
Let-dig = ALPHA / DIGIT
Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig
address-literal = "[" ( IPv4-address-literal / IPv6-address-literal ) "]"
IPv4-address-literal = Snum 3("." Snum)
IPv6-address-literal = "IPv6:" IPv6-addr
Snum = 1*3DIGIT
; representing a decimal integer value in the range 0 through 255
注意:我跳过了的定义,IPv6-addr
因为该特定RFC弄错了它,并禁止了例如::1
。正确的规范在RFC 2373中。
限制条件
您可能不使用任何现有的电子邮件验证库调用。但是,您可以使用现有的网络库来检查IP地址。
如果编写函数/方法/运算符/等效函数,则应采用字符串并返回布尔值或真实/虚假值,具体取决于您的语言。如果编写程序,则它应从stdin一行开始,并通过退出代码指示有效或无效。
测试用例
为了紧凑起见,以下测试用例在块中列出。第一块是应通过的情况:
email@domain.com
e@domain.com
firstname.lastname@domain.com
email@subdomain.domain.com
firstname+lastname@domain.com
email@123.123.123.123
email@[123.123.123.123]
"email"@domain.com
1234567890@domain.com
email@domain-one.com
_______@domain.com
email@domain.name
email@domain.co.jp
firstname-lastname@domain.com
""@domain.com
"e"@domain.com
"\@"@domain.com
email@domain
"Abc\@def"@example.com
"Fred Bloggs"@example.com
"Joe\\Blow"@example.com
"Abc@def"@example.com
customer/department=shipping@example.com
$A12345@example.com
!def!xyz%abc@example.com
_somename@example.com
_somename@[IPv6:::1]
fred+bloggs@abc.museum
email@d.com
?????@domain.com
以下测试用例不应通过:
plainaddress
#@%^%#$@#$@#.com
@domain.com
Joe Smith <email@domain.com>
email.domain.com
email@domain@domain.com
.email@domain.com
email.@domain.com
email.email.@domain.com
email..email@domain.com
email@domain.com (Joe Smith)
email@-domain.com
email@domain..com
email@[IPv6:127.0.0.1]
email@[127.0.0]
email@[.127.0.0.1]
email@[127.0.0.1.]
email@IPv6:::1]
_somename@domain.com]
email@[256.123.123.123]
为什么要
—
grc
email@d.com
和?????@domain.com
失败?
@ardnew,我添加了到相关RFC的链接。我不想内联它,因为问题已经很长了。
—
彼得·泰勒
是否也需要长度限制?整个电子邮件地址254个/本地部分64个/每个域标签63个?
—
MichaelRushton
IPv6-addr
尚未定义,并且有些测试用例具有ipv6地址,是否有验证它们的正确方法?