Reputation: 7540
I'm attempting to verify email addresses using this regex: ^.*(?=.{8,})[\w.]+@[\w.]+[.][a-zA-Z0-9]+$
It's accepting emails like [email protected]
but rejecting emails like [email protected]
(I'm using the tool at http://tools.netshiftmedia.com/regexlibrary/ for testing).
Can anybody explain why?
Upvotes: 1
Views: 5461
Reputation: 1928
Following regex works:
([A-Za-z0-9]+[-.-_])*[A-Za-z0-9]+@[-A-Za-z0-9-]+(\.[-A-Z|a-z]{2,})+
Upvotes: 0
Reputation: 9298
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.
You could adjust this part to [\w.-]+[.][a-zA-Z0-9]+$
. to make - validate in the @string.
Upvotes: 2
Reputation: 1
Use this Regex:
var email-regex = /^[^@]+@[^@]+\.[^@\.]{2,}$/;
It will accept [email protected]
as well as emails like [email protected]
.
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.
Upvotes: 1
Reputation: 11844
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]$
Upvotes: 0
Reputation: 160191
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).
Upvotes: 1