开发者

Java - Regular Expression

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 开发者_JAVA技巧contains rather make it a part of regex.


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;
    }
}


try this, this regex will only accept 1 -

((\w|-)+(\.\w+)?)+@[\w]+\-{0,1}[\w]+\.\w+
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜