Java regex email

JavaRegexEmail

Java Problem Overview


First of all, I know that using regex for email is not recommended but I gotta test this out.

I have this regex:

\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b

In Java, I did this:

Pattern p = Pattern.compile("\\b[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b");
Matcher m = p.matcher("[email protected]");
	
if (m.find())
    System.out.println("Correct!");

However, the regex fails regardless of whether the email is wel-formed or not. A "find and replace" inside Eclipse works fine with the same regex.

Any idea?

Thanks,

Java Solutions


Solution 1 - Java

FWIW, here is the Java code we use to validate email addresses. The Regexp's are very similar:

public static final Pattern VALID_EMAIL_ADDRESS_REGEX = 
    Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);

public static boolean validate(String emailStr) {
        Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);
        return matcher.find();
}

Works fairly reliably.

Solution 2 - Java

Here is RFC822 compliant regex adapted for Java:

Pattern ptr = Pattern.compile("(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z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\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*))*)?;\\s*)");
String[] emails = { "\"Fred Bloggs\"@example.com", "[email protected]", "Chuck Norris <[email protected]>", "webmaster@müller.de", "[email protected]" };
for (String email : emails) {
    System.out.println(email + " is " + (ptr.matcher(email).matches() ? "valid" : "invalid"));
}

Output:

"Fred Bloggs"@example.com is valid
user@.invalid.com is invalid
Chuck Norris <gmail@chucknorris.com> is valid
webmaster@müller.de is valid
matteo@78.47.122.114 is valid

The regex is taken from this post: Mail::RFC822::Address: regexp-based address validation. The results should coincide with online version.

Solution 3 - Java

Don't. You will never end up with a valid expression.

For example these are all valid email addresses:

"Abc\@def"@example.com
"Fred Bloggs"@example.com
"Joe\\Blow"@example.com
"Abc@def"@example.com
customer/department=shipping@examp­ le.com
$A12345@example.com
!def!xyz%abc@example.com
_somename@example.com
matteo(this is a comment).corti@example.com
root@[127.0.0.1]

Just to mention a few problems:

  • you don't consider the many forms of specifying a host (e.g, by the IP address)
  • you miss valid characters
  • you miss non ASCII domain names

Before even beginning check the corresponding RFCs

Solution 4 - Java

That's because you are forgetting case insensitivity :

Pattern regex = Pattern.compile("\\b[\\w.%-]+@[-.\\w]+\\.[A-Za-z]{2,4}\\b");

This matches your example, although it ignores many valid e-mails.

Solution 5 - Java

One another simple alternative to validate 99% of emails

public static final String EMAIL_VERIFICATION = "^([\\w-\\.]+){1,64}@([\\w&&[^_]]+){2,255}.[a-z]{2,}$";

Solution 6 - Java

This is a valid regex for validating e-mails. It's totally compliant with RFC822 and accepts IP address and server names (for intranet purposes).

public static boolean isEmailValid(String email) {
    final Pattern EMAIL_REGEX = Pattern.compile("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", Pattern.CASE_INSENSITIVE);
    return EMAIL_REGEX.matcher(email).matches();
}

Here are some output examples, when you call isEmailValid(emailVariable):

john@somewhere.com // valid
john.foo@somewhere.com // valid
john.foo+label@somewhere.com // valid (with +label - Gmail accepts it!)
john@192.168.1.10 // valid (with IP addresses)
john+label@192.168.1.10 // valid (with +label and IP address)
john.foo@someserver // valid (with no first domain level)
JOHN.FOO@somewhere.com // valid (case insensitive)
@someserver // invalid
@someserver.com // invalid
john@. // invalid
.@somewhere.com // invalid

Solution 7 - Java

I came across this post and tried some answers, however did not find one that supported all the things I needed.

  • Unicode chars in our case especial for german (ÄÖÜäöüß)
  • The gmail + feature: my.gmail+@gmail.com

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()

Solution 8 - Java

Is maching set to CASE_INSENSITIVE?

Solution 9 - Java

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();

	}
}

Solution 10 - Java

Thanks to @Jason Buberel's answer, I think lowercase letters must be validated by the RegEX. So the following is correct:

[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}

Now, both [email protected] and [email protected] are valid!
Note that \. should be \\. to escape . and have \. itself. Since, . is a meaningful character in java RegEX means all characters.

Solution 11 - Java

General Email format (RE) which include also domain like co.in, co.uk, com, outlook.com etc.

And rule says that :

  • Uppercase and lowercase English letters (a-z, A-Z)

  • Digits 0 to 9

  • Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~ Character.

  • (dot, period, full stop) provided that it is not the first or last character, and provided also that it does not appear two or more times consecutively.

     [a-zA-Z0-9]+[._a-zA-Z0-9!#$%&'*+-/=?^_`{|}~]*[a-zA-Z]*@[a-zA-Z0-9]{2,8}.[a-zA-Z.]{2,6}
    

Solution 12 - Java

you can use a simple regular expression for validating email id,

public boolean validateEmail(String email){
  return Pattern.matches("[_a-zA-Z1-9]+(\\.[A-Za-z0-9]*)*@[A-Za-z0-9]+\\.[A-Za-z0-9]+(\\.[A-Za-z0-9]*)*", email)
}

Description :

  1. [_a-zA-Z1-9]+ - it will accept all A-Z,a-z, 0-9 and _ (+ mean it must be occur)
  2. (\.[A-Za-z0-9]) - it's optional which will accept . and A-Z, a-z, 0-9( * mean its optional)
  3. @[A-Za-z0-9]+ - it wil accept @ and A-Z,a-z,0-9
  4. \.[A-Za-z0-9]+ - its for . and A-Z,a-z,0-9
  5. (\.[A-Za-z0-9]) - it occur, . but its optional

Solution 13 - Java

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();
}

Solution 14 - Java

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;
			else
				email_valid = false;

			// checks for NOT words,numbers,underscore and whitespace.
			// checks if special characters present
			if ((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;
			else
				password_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();

	}

}

Solution 15 - Java

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();
    }

Solution 16 - Java

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.

Solution 17 - Java

Try the below code for email is format of

jsmith@example.com

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}$

Solution 18 - Java

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.

End_user@live.com
End.u@exm-tech.net
enduser9876@gmail.in
end_user@mywebsite.ac.in.gui
Another984.User2@mail.edu.sg
Another987_User5@mail.show.au
Slow_User@example_domain.au.in
iamthemostsimpleremailhere@example.com

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!

Solution 19 - Java

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.

Solution 20 - Java

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

Solution 21 - Java

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

Solution 22 - Java

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;

@Before
public void setUp() throws Exception {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    validator = factory.getValidator();
}

@Test
public 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());
                    }
            );
}

@Test
public 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);
}

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTu HoangView Question on Stackoverflow
Solution 1 - JavaJason BuberelView Answer on Stackoverflow
Solution 2 - JavaejboyView Answer on Stackoverflow
Solution 3 - JavaMatteoView Answer on Stackoverflow
Solution 4 - JavaFailedDevView Answer on Stackoverflow
Solution 5 - JavaArmer B.View Answer on Stackoverflow
Solution 6 - JavashimataiView Answer on Stackoverflow
Solution 7 - JavaMartinView Answer on Stackoverflow
Solution 8 - JavaXaerxessView Answer on Stackoverflow
Solution 9 - JavaChanaka udayaView Answer on Stackoverflow
Solution 10 - JavaMohsen AbasiView Answer on Stackoverflow
Solution 11 - JavaHitesh KalwaniView Answer on Stackoverflow
Solution 12 - JavaVivek HandeView Answer on Stackoverflow
Solution 13 - JavaAlex HodsonView Answer on Stackoverflow
Solution 14 - JavaAnu SathiyaView Answer on Stackoverflow
Solution 15 - JavaNeoView Answer on Stackoverflow
Solution 16 - JavaNabil A.View Answer on Stackoverflow
Solution 17 - JavacharanView Answer on Stackoverflow
Solution 18 - JavaArifMustafaView Answer on Stackoverflow
Solution 19 - Javaprakhar9293View Answer on Stackoverflow
Solution 20 - JavaFridjato Part FridjatView Answer on Stackoverflow
Solution 21 - JavaKrzysztofView Answer on Stackoverflow
Solution 22 - JavaOleksandr YefymovView Answer on Stackoverflow