Java regex email

2019-01-01 08:13发布

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("foobar@gmail.com");

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 regex email
16条回答
看淡一切
2楼-- · 2019-01-01 08:51

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.

查看更多
宁负流年不负卿
3楼-- · 2019-01-01 08:53

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();
    }
查看更多
与风俱净
4楼-- · 2019-01-01 08:53

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@yahoo.com", "email-100@yahoo.com",
        "Email.100@yahoo.com", "email111@email.com", "email-100@email.net",
        "email.100@email.com.au", "emAil@1.com", "email@gmail.com.com",
        "email+100@gmail.com", "emAil-100@yahoo-test.com", "email_100@yahoo-test.ABC.CoM"};
private static final String[] INVALID_EMAILS = new String[]{"あいうえお@example.com", "email@111",
        "email", "email@.com.my", "email123@gmail.", "email123@.com", "email123@.com.com",
        ".email@email.com", "email()*@gmAil.com", "eEmail()*@gmail.com", "email@%*.com", "email..2002@gmail.com",
        "email.@gmail.com", "email@email@gmail.com", "email@gmail.com."};
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);
}

}

查看更多
只若初见
5楼-- · 2019-01-01 08:54

One another simple alternative to validate 99% of emails

public static final String EMAIL_VERIFICATION = "^([\\w-\\.]+){1,64}@([\\w&&[^_]]+){2,255}.[a-z]{2,}$";
查看更多
素衣白纱
6楼-- · 2019-01-01 08:55

Is maching set to CASE_INSENSITIVE?

查看更多
泛滥B
7楼-- · 2019-01-01 08:55

Try the below code for email is format of

jsmith@example.com

1st part -jsmith 2nd part -@example.com

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}$
查看更多
登录 后发表回答