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.

[email protected]

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

2
  • 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 Commented Feb 11, 2013 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. Commented Feb 11, 2013 at 17:47

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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...

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.