EHarpham EHarpham - 3 months ago 15
Java Question

Validate only a specific email with regex in java

I am trying to validate an email address. I currently have:

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,})$";


This will validate any email but I am trying to validate only a company specific email e.g.

myname@specificemail.com

The email will always end with .com but i would like the ability to change the company name at a later date with a different specific string e.g. @anotheremail.com, @somethingelse.com

Can anyone help with with the syntax?

Thanks

Answer Source

You can validate company specific email using this regex:

private static final String coDomain = "specificemail.com";
private static final String EMAIL_PATTERN = 
    "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
    + Pattern.quote(coDomain) + "$";

Later on just change the value of coDomain variable to some other name as needed.