Java email address validation (Regular Expression)

I'm working on a java based email address validator using regular expressions, and it seems to be working for the most part, but I have noticed two things that don't work properly.

Here is my regular expression

^([_a-zA-Z0-9-]+)(.[_a-zA-Z0-9-]+)*@([a-zA-Z0-9-]+)(.[a-zA-Z0-9-]+)*(.[a-zA-Z]{2,6})$

The two things that don't work with it are that it allows spaces, which I'm not sure why.  Although if there are two spaces in a row, then it does say theres a problem.

Secondly, the last part of it, where I specify a-zA-Z {2,6} is for the ".com" part of the email, where the length has to be between 2, and 6.  However when i run an email address it doesn't check the length properly.  the email address test@this.a, and it fails it properly because of the length 1.  But if I use the email test@this.asdfgasd it passes it, even though its of length 8.

I know how to get around the space problem by using a tokenizer of " ", and checking the tokenCount.  But is there a way to do it in the regularexpression?  and how do I fix the length part for the final piece?

Thanks
zaqAsked:
Who is Participating?
 
CEHJCommented:
"." will match a space. It should be "\\."

Check

    System.out.println(" ".matches("\\."));
    System.out.println(" ".matches("."));


Why don't you use an off-the-shelf RE?
0
 
CEHJCommented:
>>Why don't you use an off-the-shelf RE?

btw, i consider myself pretty strong with REs, but wouldn't dream of concocting my own email RE. Try

final String EMAIL_RE = "^[A-Za-z0-9](([_\\.\\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\\.\\-]?[a-zA-Z0-9]+)*)\\.([A-Za-z]{2,})$";
 
0
 
zaqAuthor Commented:
i looked online, and this expression was from a php site.  all I did was converted it to java, and aparently incorrectly at that.

seems my understanding of regular expressions was incorrect.

Changing it to: ^([_a-zA-Z0-9-]+)(\\.[_a-zA-Z0-9-]+)*@([a-zA-Z0-9-]+)(\\.[a-zA-Z0-9-]+)*(\\.[a-zA-Z]{2,6})$ made things work fine.  So the escape character of \\ in front of the . cleared up the space issue, and the count.  

Thanks.
0
 
CEHJCommented:
8-)

>>i looked online, and this expression was from a php site

Ah OK - it lost something in translation ;-)
0
 
zaqAuthor Commented:
yep.  my translation was just bad.

Thanks again for the help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.