Search code examples
javaregexemail-validation

Removing trailing characters after email address with Regex


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?


Solution

  • 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,})[.,]?$";
                                                       ^^^^^