Reputation: 652
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
Reputation: 28541
To check your own format, this should work:
Pattern p = Pattern.compile("[a-zA-Z0-9_]+[\\.]{0,1}[a-zA-Z0-9_]*");
Test it on http://www.regexplanet.com/simple/index.html
Upvotes: 0
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
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