Amit Dalal
Amit Dalal

Reputation: 652

validate e-mail field using regex

I need to check if a string (local part of email address) has nothing except:

How do I do it using Java regex?

Example: a_1_b.c and a_b_1, should be okay ,but 1.a_b.2 and 1_a*3 should be discarded.

Upvotes: 2

Views: 5758

Answers (5)

Amit Dalal
Amit Dalal

Reputation: 652

The regex [\w]*\.[\w]+|[\w]+ should work, I guess.

Upvotes: 1

Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28541

To check your own format, this should work:

Pattern p = Pattern.compile("[a-zA-Z0-9_]+[\\.]{0,1}[a-zA-Z0-9_]*");
  • a_1_b.c should be okay
  • a_1b also
  • 1.a_b.2 and 1_a*3 should get rejected

Test it on http://www.regexplanet.com/simple/index.html

Upvotes: 0

corsiKa
corsiKa

Reputation: 82559

Assuming there also has to be exactly one '@', and it must come before (but not immediately before) the single '.', you could do

final static private String charset = "[a-zA-Z0-9_]"; // separate this out for future fixes
final static priavte String regex = charset + "+@" + charset + "+\." + charset + "+";

boolean validEmail(String email) {
    return email.matches(regex);
}

Upvotes: 0

WhiteFang34
WhiteFang34

Reputation: 72039

If you want to verify email correctness you might want to just rely on the JavaMail API to do it for you. Then you don't need to worry about encoding the details of the RFC 822 specification into a regex. Not to mention if you're dealing with email addresses you likely want an easy way to send them, and the library has that too. You could verify that an email address is valid with simply:

try {
    new InternetAddress(email).getAddress();
} catch (AddressException e) {
    // it's not valid
}

Upvotes: 8

bastianwegge
bastianwegge

Reputation: 2498

Your should find more information here.

Upvotes: 2

Related Questions