Note that \. should be \\. to escape . and have \. itself. Since, . is a meaningful character in java RegEX means all characters.
Is maching set to CASE_INSENSITIVE?
You can use this method for validating email address in java.
public class EmailValidator {private Pattern pattern;private Matcher matcher;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,})$";public EmailValidator() {pattern = Pattern.compile(EMAIL_PATTERN);}/*** Validate hex with regular expression* * @param hex* hex for validation* @return true valid hex, false invalid hex*/public boolean validate(final String hex) {matcher = pattern.matcher(hex);return matcher.matches();}}
I came across this post and tried some answers, however did not find one that supported all the things I needed.
I found a comprehensive listing of patterns at https://www.baeldung.com/java-email-validation-regex where I found the unicode and gmail approaches:
uniCodeRegex = "^(?=.{1,64}@)[\\p{L}0-9_-]+(\\.[\\p{L}0-9_-]+)*@" + "[^-][\\p{L}0-9-]+(\\.[\\p{L}0-9-]+)*(\\.[\\p{L}]{2,})$";gmailRegex = "^(?=.{1,64}@)[A-Za-z0-9\\+_-]+(\\.[A-Za-z0-9\\+_-]+)*@" + "[^-][A-Za-z0-9\\+-]+(\\.[A-Za-z0-9\\+-]+)*(\\.[A-Za-z]{2,})$";
TL,DR: and combined them by replacing A-Za-z
with \\p{L}
for unicode letters
combined = "^(?=.{1,64}@)[\\p{L}0-9\\+_-]+(\\.[\\p{L}0-9\\+_-]+)*@"+ "[^-][\\p{L}0-9\\+-]+(\\.[\\p{L}0-9\\+-]+)*(\\.[\\p{L}]{2,})$"
Kotlin test example:
val p = Pattern.compile(patternRegex)assertThat(p.matcher("[email protected]").find()).isTrue()
General Email format (RE) which include also domain like co.in, co.uk, com, outlook.com etc.
And rule says that :
(dot, period, full stop) provided that it is not the first or lastcharacter, and provided also that it does not appear two or moretimes consecutively.
[a-zA-Z0-9]+[._a-zA-Z0-9!#$%&'*+-/=?^_`{|}~]*[a-zA-Z]*@[a-zA-Z0-9]{2,8}.[a-zA-Z.]{2,6}
I have tested this below regular expression
for single and multiple consecutive dots in domain
name -
([A-Za-z0-9-_.]+@[A-Za-z0-9-_]+(?:\.[A-Za-z0-9]+)+)
and here are the examples which were completely fulfilled by above regex
.
[email protected][email protected][email protected][email protected][email protected][email protected]Slow_User@example_domain.au.in[email protected]
I have tried to cover maximum commonly used email id's validation
by this above illustrated regex
and yet working...
If you still know some consequentially used email id's
had left here, please let me know in comment section!
Modification of Armer B. answer which didn't validate emails ending with '.co.uk'
public static boolean emailValidate(String email) {Matcher matcher = Pattern.compile("^([\\w-\\.]+){1,64}@([\\w&&[^_]]+){2,255}(.[a-z]{2,3})+$|^$", Pattern.CASE_INSENSITIVE).matcher(email);return matcher.find();}
import java.util.Scanner;public class CheckingTheEmailPassword {public static void main(String[] args) {String email = null;String password = null;Boolean password_valid = false;Boolean email_valid = false;Scanner input = new Scanner(System.in);do {System.out.println("Enter your email: ");email = input.nextLine();System.out.println("Enter your passsword: ");password = input.nextLine();// checks for words,numbers before @symbol and between "@" and ".".// Checks only 2 or 3 alphabets after "."if (email.matches("[\\w]+@[\\w]+\\.[a-zA-Z]{2,3}"))email_valid = true;elseemail_valid = false;// checks for NOT words,numbers,underscore and whitespace.// checks if special characters presentif ((password.matches(".*[^\\w\\s].*")) &&// checks alphabets present(password.matches(".*[a-zA-Z].*")) &&// checks numbers present(password.matches(".*[0-9].*")) &&// checks length(password.length() >= 8))password_valid = true;elsepassword_valid = false;if (password_valid && email_valid)System.out.println(" Welcome User!!");else {if (!email_valid)System.out.println(" Re-enter your email: ");if (!password_valid)System.out.println(" Re-enter your password: ");}} while (!email_valid || !password_valid);input.close();}}
You can use a simple regular expression for validating email id,
public boolean validateEmail(String email){return Pattern.matches("[_a-zA-Z0-9]+(\\.[A-Za-z0-9]*)*@[A-Za-z0-9]+\\.[A-Za-z0-9]+(\\.[A-Za-z0-9]*)*", email)}
Description:
Regex : ^[\\w!#$%&’*+/=?
{|}~^-]+(?:\.[\w!#$%&’*+/=?{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$
public static boolean isValidEmailId(String email) {String emailPattern = "^[\\w!#$%&’*+/=?`{|}~^-]+(?:\\.[\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";Pattern p = Pattern.compile(emailPattern);Matcher m = p.matcher(email);return m.matches();}
If you want to allow non-latain characters, this one works quite well for me.
"^[\\p{L}\\p{N}\\._%+-]+@[\\p{L}\\p{N}\\.\\-]+\\.[\\p{L}]{2,}$"
It does not allow IP's after the @ but most valid email in the from of [email protected]
could be validated with it.\p{L}
validates UTF-Letters and \p{N}
validates UTF-Numbers. You can check this doc for more information.
Regex for Facebook-like validation:
public static final String REGEX_EMAIL_VALIDATION = "^[\\w-\\+]+(\\.[\\w]+)*@[\\w-]+(\\.[\\w]+)*(\\.[a-zA-Z]{2,})$";
Dto for Unit tests(with Lombok):
@Data@Accessors(chain = true)@FieldDefaults(level = AccessLevel.PRIVATE)public class UserCreateDto {@NotNull@Pattern(regexp = REGEX_EMAIL_VALIDATION)@Size(min = 1, max = 254)String email;}
Valid/invalid emails below with Unit tests:
public class UserCreateValidationDtoTest {private static final String[] VALID_EMAILS = new String[]{"[email protected]", "[email protected]","[email protected]", "[email protected]", "[email protected]","[email protected]", "[email protected]", "[email protected]","[email protected]", "[email protected]", "[email protected]"};private static final String[] INVALID_EMAILS = new String[]{"あいうえお@example.com", "email@111","email", "[email protected]", "email123@gmail.", "[email protected]", "[email protected]","[email protected]", "email()*@gmAil.com", "eEmail()*@gmail.com", "email@%*.com", "[email protected]","[email protected]", "email@[email protected]", "[email protected]."};private Validator validator;@Beforepublic void setUp() throws Exception {ValidatorFactory factory = Validation.buildDefaultValidatorFactory();validator = factory.getValidator();}@Testpublic void emailValidationShouldBeValid() throws Exception {Arrays.stream(VALID_EMAILS).forEach(email -> {Set<ConstraintViolation<UserCreateDto>> violations = validateEmail(new UserCreateDto().setEmail(email));System.out.println("Email: " + email + ", violations: " + violations);Assert.assertTrue(violations.isEmpty());});}@Testpublic void emailValidationShouldBeNotValid() throws Exception {Arrays.stream(INVALID_EMAILS).forEach(email -> {Set<ConstraintViolation<UserCreateDto>> violations = validateEmail(new UserCreateDto().setEmail(email));System.out.println("Email: " + email + ", violations: " + violations);Assert.assertTrue(!violations.isEmpty());});}private Set<ConstraintViolation<UserCreateDto>> validateEmail(UserCreateDto user) {String emailFieldName = "email";return validator.validateProperty(user, emailFieldName);}
}
Try the below code for email is format of
[email protected]
1st part -jsmith
2nd part [email protected]
1. In the 1 part it will allow 0-9,A-Z,dot sign(.),underscore sign(_)2. In the 2 part it will allow A-Z, must be @ and .^[a-zA-Z0-9_.]+@[a-zA-Z.]+?\.[a-zA-Z]{2,3}$
String emailRegex = "[a-zA-Z0-9_.]+@[a-zA-Z0-9]+.[a-zA-Z]{2,3}[.] {0,1}[a-zA-Z]+";Pattern.matches(emailRegex,"You_Input_Mail_Id");
This is the regex to match valid email addresses.
You can checking if emails is valid or no by using this libreries, and of course you can add array for this folowing project.
import org.apache.commons.validator.routines.EmailValidator;public class Email{public static void main(String[] args){EmailValidator email = EmailVlidator.getInstance();boolean val = email.isValid("[email protected]");System.out.println("Mail is: "+val);val = email.isValid("hans.riguer.hotmsil.com");System.out.print("Mail is: "+val");}}
output :
Mail is: true
Mail is : false
If you use Java Bean Validation, an email can be validated with javax.validation.constraints.Email
annotation.
If you want to do it manually, you can see how Hibernate Validator (Java Bean Validation implementation) done it:
https://github.com/hibernate/hibernate-validator/blob/master/engine/src/main/java/org/hibernate/validator/internal/constraintvalidators/AbstractEmailValidator.java
You can also use the solution provided by
org.hibernate.validator.constraints.impl.EmailValidatorpublic class EmailValidator implements ConstraintValidator<Email, String> {private static String ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~-]";private static String DOMAIN = "(" + ATOM + "+(\\." + ATOM + "+)*";private static String IP_DOMAIN = "\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\]";private java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("^" + ATOM + "+(\\." + ATOM + "+)*@"+ DOMAIN+ "|"+ IP_DOMAIN+ ")$",java.util.regex.Pattern.CASE_INSENSITIVE);public void initialize(Email annotation) {}public boolean isValid(String value, ConstraintValidatorContext context) {if ( value == null || value.length() == 0 ) {return true;}Matcher m = pattern.matcher( value );return m.matches();}}