2

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

EHarpham
  • 602
  • 1
  • 17
  • 34
  • 1
    Not really duplicate if that regex validates the email addresses you want to accept, but please note that RFC-compliant email validation can be tricky, as answered in this question: [Using a regular expression to validate an email address](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address) – Xavi López Feb 11 '13 at 17:24
  • 1
    The main problem with the validation with a dynamic regular expression is that it always will be compiled over and over again. It is best to have a cache of already compiled patterns. – Paul Vargas Feb 11 '13 at 17:47

4 Answers4

2

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.

M. Witney
  • 45
  • 3
  • 12
anubhava
  • 761,203
  • 64
  • 569
  • 643
0
// be careful with regex meta characters in the company name.
public static String emailFromCompanyPatternString(String company) {
    return "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
    + company + (\\.[A-Za-z]{2,})$";
}
jlordo
  • 37,490
  • 6
  • 58
  • 83
0

Perhaps something like this:

public static Pattern getEmailValidator( String domain ) {
    return Pattern.compile( "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + domain );
}

public void someMethodThatNeedsToValidatEmail( String domain, String email ) {
    return getEmailValidator( domain ).matches( email );
}

Note, this is untested code...

Lucas
  • 14,227
  • 9
  • 74
  • 124
0

I am using this is for specific ending domain. Simply replace your ending domain with "@gmail.com"

private static final String EMAIL_REGEX1 = 
"^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@gmail.com";

private static final String EMAIL_REGEX1 = 
"^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@somethingelse.com";

Visit https://ideone.com/UUTnky for Full Regex Email Validation Java Implementation.