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 / for testing).
Can anybody explain why?
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://toolsshiftmedia./regexlibrary/ for testing).
Can anybody explain why?
Share Improve this question asked Nov 18, 2011 at 5:05 Alex GhiculescuAlex Ghiculescu 7,5403 gold badges29 silver badges42 bronze badges 1- 2 This might be of use to you:programmers.stackexchange./questions/78353/… – Levi Morrison Commented Nov 18, 2011 at 5:08
5 Answers
Reset to default 2Here is the explaination:
In your regualr expression, the part matches a-bc@def. and abc@de-f. 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.
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 [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.
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]$
Following regex works:
([A-Za-z0-9]+[-.-_])*[A-Za-z0-9]+@[-A-Za-z0-9-]+(\.[-A-Z|a-z]{2,})+