Link to home
Start Free TrialLog in
Avatar of zaq
zaq

asked on

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
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>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,})$";
 
Avatar of zaq
zaq

ASKER

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

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

Ah OK - it lost something in translation ;-)
Avatar of zaq

ASKER

yep.  my translation was just bad.

Thanks again for the help.