0
votes

I am using regex to identify if a string is a valid email address or not. Pattern:

private static final String EMAIL_PATTERN = 
    "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
    + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

The problem is that this regex pattern cannot correctly identify the email address if it contains a trailing character. e.g: "[email protected]." or "[email protected],"

Do you know of a regex pattern that can take this into account?

1
Well, [email protected], (note the trailing comma) is an invalid email address... - fge
This regex produces a lot of false negative, see: en.wikipedia.org/wiki/Email_address#Valid_email_addresses - Toto
Also take a look at this question: stackoverflow.com/questions/600733/… - gdiazc

1 Answers

1
votes

Before the $ sign, use [.,]? or any other punctuation(inside that []) if you want to be there to overcome this.

+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})[.,]?$";
                                                   ^^^^^