简体   繁体   中英

Email verification regex failing on hyphens

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?

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.

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).

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.

Following regex works:

([A-Za-z0-9]+[-.-_])*[A-Za-z0-9]+@[-A-Za-z0-9-]+(\.[-A-Z|a-z]{2,})+

相反,您可以使用这样的正则表达式来允许任何电子邮件地址。

^[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]$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM