Javascript email regex

2020-05-03 10:46发布

问题:

I've come across a description of a decent email regex.

/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/

But I would also like to include some punctuation characters into the first part of the email whilst retaining the rest of the functionality (such as no repeated .)

The best I have come up with so far is:

([\/!#$%&'*+-=?^_`{|}~]*\w+)([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,40})+$

But this will not allow punctuation at the end of the first part of the email.

I find regex so confusing, does anyone know how to properly implement this?

Example:

Yes email@domain.com
Yes firstname.lastname@domain.com
Yes email@subdomain.domain.com
Yes firstname+lastname@domain.com
Yes email@123.123.123.123
Yes email@[123.123.123.123]
Yes "email"@domain.com
Yes 1234567890@domain.com
Yes email@domain-one.com
Yes _______@domain.com
Yes email@domain.name
Yes email@domain.co.jp
Yes firstname-lastname@domain.com
No  plainaddress
No  #@%^%#$@#$@#.com
No  @domain.com
No  Joe Smith <email@domain.com>
No  email@domain@domain.com
No  .email@domain.com
No  email.@domain.com
No  email..email@domain.com
No  あいうえお@domain.com
No  email@domain.com (Joe Smith)
No  email@domain
No  email@-domain.com
No  email@domain.web

回答1:

This is my closest attempt now, I think it is roughly correct

^[a-zA-Z0-9_!#$%&‘*\=\+\/\?^{|}~]+([\.-]?[a-zA-Z0-9_!#$%&‘*\=\+\/\?^{|}~]+)*@\w+([\.-]?\w+)*(\.\w{2,50})+$


回答2:

You need to replace \w with its equivalent [A-Za-z0-9_] and escape all the special characters from here.

try this:-

/^[\/\!#\$\%&'\*\+\-\=\?\^_`\{\|\}~A-Za-z0-9]+[\.-]?[\/\!#\$\%&'\*\+\-\=\?\^_`\{\|\}~A-Za-z0-9]*@\w+([\.-]?\w+)*(\.\w{2,40})+$/


回答3:

([a-zA-Z0-9\-\_\"]+)([\_\.\-\+{1}])?([a-zA-Z0-9\-\"\_]+)\@([a-zA-Z0-9\[]+)([\-])?([a-zA-Z0-9]+)?([\.])([a-zA-Z0-9\.\]]+)

Jack, the expression I have mentioned above will provide the solution for this problem. This will give the desired results according to the question.