0

I have a regular expression to validate email:

Validemail = ^[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s-\\.]([^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s\\.]|\\.(?!\\.+?))*[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s-\\.]@[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s\\.]*[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s-\\.]\\.(?!\\.+?)[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\0-9\\s-\\_]{2,40}$$

This validation is accepting EG: kate@stack---overlow.com

However I want to restrict the domain name after @ and before . so have only 1 hyphen.

Update:

I would not prefer making that check using contains rather make it a part of regex.

Community
  • 1
  • 1

2 Answers2

3

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;
    }
}
Community
  • 1
  • 1
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
  • Yeah what iam saying is subsequnet hyphens we shld discourage. – jaisri_88 May 11 '11 at 08:49
  • If you just want to prevent sequences of hyphens then you could change the check here to `return !address.contains("--");` much like Peter suggested. The point is here though is to use the JavaMail API to do the hard work of validating an email address. Then you can easily perform your additional restriction(s) afterwards. – WhiteFang34 May 11 '11 at 08:55
0

try this, this regex will only accept 1 -

((\w|-)+(\.\w+)?)+@[\w]+\-{0,1}[\w]+\.\w+
AabinGunz
  • 12,109
  • 54
  • 146
  • 218