Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate e-mail field using regex

Tags:

java

regex

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

  • letters (a-zA-Z)
  • numbers (0-9)
  • underscores
  • at most one dot (.)

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.

like image 223
Amit Dalal Avatar asked Feb 17 '26 11:02

Amit Dalal


1 Answers

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
}
like image 172
WhiteFang34 Avatar answered Feb 18 '26 23:02

WhiteFang34



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!