Is this email regex complete [closed]
I'm following these specifications from wikipedia.
[^\.]([a-zA-Z\d\!\#\$%&\'\*\+\-\/\=\?\^_`\{|\}\~]|[^\.][\.]{1})+[^\.]@[a-zA-Z\d\-\_]+(\.[a-z]{2,5}){1,2}
How can it be improved/shortened?
PS:
I know there are multitudes of email validators already made, this is strictly for my own learning in regards to regex. Thanks.
Domain names cannot contain underscores, so you should remove this from the part after the @
.
What about sub-domains? I don't think the given regex will match someone@subdomain.example.com
Personally, I've always used /^[a-zA-Z0-9._%+-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}$/
which does not match the entire RFC-2822 specification, but does the job for >99.9% of real-world email addresses.
If you want to learn about validating email addresses with regular expressions and some of the trade-offs, read this article http://www.regular-expressions.info/email.html
Another good source are widely used open source libraries or applications that contain functions for validating email.
Your regex indeed doesn't match emails with subdomains, which you can achieve by adding the dot to the 1st character class after the @ sign
[^\.]([a-zA-Z\d\!\#\$%&\'\*\+\-\/\=\?\^_`\{|\}\~]|[^\.][\.]{1})+[^\.]@[a-zA-Z\d\-\_\.]+(\.[a-z]{2,5}){1,2}
精彩评论