Reputation: 1
I have a regular expression to validate email:
Validemail = ^[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s-\\.]([^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s\\.]|\\.(?!\\.+?))*[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s-\\.]@[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s\\.]*[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s-\\.]\\.(?!\\.+?)[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\0-9\\s-\\_]{2,40}$$
This validation is accepting EG: [email protected]
However I want to restrict the domain name after @
and before .
so have only 1 hyphen.
I would not prefer making that check using contains
rather make it a part of regex.
Upvotes: 0
Views: 245
Reputation: 12347
try this, this regex will only accept 1 -
((\w|-)+(\.\w+)?)+@[\w]+\-{0,1}[\w]+\.\w+
Upvotes: 0
Reputation: 72049
I'd recommend first validating the email address with the JavaMail API, as described in this answer: validate e-mail field using regex. That way you don't have to deal with a complicated regex to handle all of the details of the RFC 822 specification on email addresses.
Once it passes that, then add your additional check for a single hyphen after @
and before .
, e.g.:
public boolean isValidEmail(String email) {
try {
String address = new InternetAddress(email).getAddress();
return address.matches(".*@[^-]*-{0,1}[^-]*\\..*");
} catch (AddressException e) {
// you should probably log here for debugging
return false;
}
}
Upvotes: 3