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,
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 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}
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();
}
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.
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 :
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.
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:
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.
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();
}
}
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();
}
Is maching set to CASE_INSENSITIVE?
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)
:
[email protected] // valid
[email protected] // valid
[email protected] // valid (with +label - Gmail accepts it!)
[email protected] // valid (with IP addresses)
[email protected] // valid (with +label and IP address)
john.foo@someserver // valid (with no first domain level)
[email protected] // valid (case insensitive)
@someserver // invalid
@someserver.com // invalid
john@. // invalid
[email protected] // invalid
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|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\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[ \\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
[email protected] is invalid
Chuck Norris <[email protected]> is valid
webmaster@müller.de is valid
[email protected] is valid
The regex is taken from this post: Mail::RFC822::Address: regexp-based address validation. The results should coincide with online version.
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[]{"[email protected]", "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);
}
}
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}$
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!
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
One another simple alternative to validate 99% of emails
public static final String EMAIL_VERIFICATION = "^([\\w-\\.]+){1,64}@([\\w&&[^_]]+){2,255}.[a-z]{2,}$";
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();
}
}
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
[email protected]
!def!xyz%[email protected]
[email protected]
matteo(this is a comment)[email protected]
root@[127.0.0.1]
Just to mention a few problems:
Before even beginning check the corresponding RFCs
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.
Source: Stackoverflow.com