Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression for email validation in Java

I am using the follwoing regular expression

(".+@.+\\.[a-z]+")

Bit it accepts #@#.com as a valid email. What's the pattern I should use?

like image 589
aks Avatar asked May 04 '10 05:05

aks


People also ask

How do I validate an email address in regex?

To get a valid email id we use a regular expression /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.

What is the simplest regular expression for email validation?

Regex : ^(.+)@(.+)$ This one is simplest and only cares about '@' symbol. Before and after '@' symbol, there can be any number of characters. Let's see a quick example to see what I mean.

How can we write a generalized regular expressions for email ID validation in Java?

[a-zA-Z0-9+_. -] matches one character from the English alphabet (both cases), digits, “+”, “_”, “.” and, “-” before the @ symbol. + indicates the repetition of the above-mentioned set of characters one or more times. @ matches itself.


2 Answers

You should use apache-commons email validator. You can get the jar file from here.

Here is a simple example of how to use it:

import org.apache.commons.validator.routines.EmailValidator;

boolean isValidEmail = EmailValidator.getInstance().isValid(emailAddress);
like image 93
CoolBeans Avatar answered Sep 25 '22 12:09

CoolBeans


Here's a web page that explains that better than I can: http://www.regular-expressions.info/email.html (EDIT: that appears to be a bit out of date since it refers to RFC 2822, which has been superseded by RFC 5322)

And another with an interesting take on the problem of validation: http://www.markussipila.info/pub/emailvalidator.php

Generally the best strategy for validating an email address is to just try sending mail to it.

like image 39
David Z Avatar answered Sep 25 '22 12:09

David Z