Email verification regex failing on hyphens

2020-07-27 16:30发布

问题:

I'm attempting to verify email addresses using this regex: ^.*(?=.{8,})[\w.]+@[\w.]+[.][a-zA-Z0-9]+$

It's accepting emails like a-bc@def.com but rejecting emails like abc@de-f.com (I'm using the tool at http://tools.netshiftmedia.com/regexlibrary/ for testing).

Can anybody explain why?

回答1:

Here is the explaination:

In your regualr expression, the part matches a-bc@def.com and abc@de-f.com is [\w.]+[.][a-zA-Z0-9]+$

It means:

  • There should be one or more digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks) or '.'. See the reference of '\w'

  • It is followed by a '.',

  • Then it is followed one or more characters within the collection a-zA-Z0-9.

So the - in de-f.com doesn't matches the first [\w.]+ format in rule 1.

The modified solution

You could adjust this part to [\w.-]+[.][a-zA-Z0-9]+$. to make - validate in the @string.



回答2:

Because after the @ you're looking for letters, numbers, _, or ., then a period, then alphanumeric. You don't allow for a - anywhere after the @.

You'd need to add the - to one of the character classes (except for the single literal period one, which I would have written \.) to allow hyphens.

\w is letters, numbers, and underscores.

A . inside a character class, indicated by [], is just a period, not any character.

In your first expression, you don't limit to \w, you use .*, which is 0+ occurrences of any character (which may not actually be what you want).



回答3:

Use this Regex:

var email-regex = /^[^@]+@[^@]+\.[^@\.]{2,}$/;

It will accept a-bc@def.com as well as emails like abc@de-f.com.

You may also refer to a similar question on SO:

Why won't this accept email addresses with a hyphen after the @?

Hope this helps.



回答4:

Instead you can use a regex like this to allow any email address.

^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$