什么是一个好的正则表达式来捕捉错误的电子邮件地址?

当用户在我的网站上创建一个帐户,我想使电子邮件不接受 每个输入服务器验证。

我会发送一个确认,在某种程度上做一个 握手验证

我正在寻找 一些简单的,不是最好的,但不太简单,不验证任何东西。我不知道限制在哪里,因为任何正则表达式都不会进行正确的验证,因为不可能用正则表达式进行验证。

我试图限制正则表达式固有的语法和视觉复杂性,因为在这种情况下,任何表达式都是正确的。

我可以使用什么 regexp 来执行此操作?

70538 次浏览

It's possible to write a regular expression that only accept email addresses that follow the standards. However, there are some email addresses out there that doesn't strictly follow the standards, but still work.

Here are some simple regular expressions for basic validation:

Contains a @ character:

@

Contains @ and a period somewhere after it:

@.*?\.

Has at least one character before the @, before the period and after it:

.+@.+\..+

Has only one @, at least one character before the @, before the period and after it:

^[^@]+@[^@]+\.[^@]+$

User AmoebaMan17 suggests this modification to eliminate whitespace:

^[^@\s]+@[^@\s]+\.[^@\s]+$

And for accepting only one period [external edit: not recommended, does not match valid email adresses]:

^[^@\s]+@[^@\s\.]+\.[^@\.\s]+$

Take your pick.

Here's the one that complies with RFC 2822 Section 3.4.1 ...

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

Just in case you are curious. :)

^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$

  • Only 1 @
  • Several domains and subdomains

I think this little tweak to the expression by AmoebaMan17 should stop the address from starting/ending with a dot and also stop multiple dots next to each other. Trying not to make it complex again whilst eliminating a common issue.

(?!.*\.\.)(^[^\.][^@\s]+@[^@\s]+\.[^@\s\.]+$)

It appears to be working (but I am no RegEx-pert). Fixes my issue with users copy&pasting email addresses from the end of sentences that terminate with a period.

i.e: Here's my new email address tabby@coolforcats.com.