English 中文(简体)
Java regex email
原标题:Java regex email

首先,我知道,不建议使用电子邮件的管制,但I gotta检验这一点。

我有这一规定:

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

在 Java,我这样做:

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!");

然而,不论电子邮件是否知情,都未能成功。 Eclipse内部的“定购取和替换”同一种reg。

任何想法?

感谢

最佳回答

妇联在此是我们用来验证电子邮件地址的 Java法。 The Regexps 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.matches();
}

工程相当可靠。

问题回答

RFC822 符合要求,适用于 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\\]|\\.|(?:(?:\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])*(?:[^()<>@,;:\\".\[\] \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])*)?(?:[^()<>@,;:\\".\[\] \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])*))*\>(?:(?:\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])*))*@(?:(?:\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\\]|\\.|(?:(?:\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])*(?:[^()<>@,;:\\".\[\] \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])*)?(?:[^()<>@,;:\\".\[\] \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])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*(?:(?:[^()<>@,;:\\".\[\] \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\\]|\\.|(?:(?:\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])*(?:[^()<>@,;:\\".\[\] \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])*)?(?:[^()<>@,;:\\".\[\] \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])*))*\>(?:(?:\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"));
}

产出:

"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 accreditation。 成果应当与

<>Dont> 你们永远不会以有效的表述结束。

例如,所有有效的电子邮件地址:

"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]

仅提及几个问题:

  • 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

甚至在开始检查相应的区域渔委会之前

这是因为你正在听从不敏感的情况:

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

这符合你的榜样,尽管它忽略了许多有效的电子邮件。

验证99%电子邮件的另一种简单选择

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

这是有效的电子邮件验证制度。 它完全遵守第822号行政指示,接受IP地址和服务器名称(用于内联网)。

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

下面是一些产出例子,请打电话is EmailValid(电子邮箱:Variable):

[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

由于“Jason Buberel”的回答,我认为下几封信必须由RegEX验证。 因此:

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

Is maching set to ?

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

    }
}

电子邮件总格式(RE)也包括共同点、共同点、 com、展望等领域。

规则指出:

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

我在<条码>中测试了单项和多份连续墨标的<条/条码>。 姓名

([A-Za-z0-9-_.]+@[A-Za-z0-9-_]+(?:.[A-Za-z0-9]+)+)

这里的例子是以上“代码>regex所完全完成的例子。

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
Slow_User@example_domain.au.in
[email protected]

我试图涵盖通用。 E/CN.15/2008/L.10。

如果你仍然知道有人因此使用<代码>,电子邮箱:id s。 请让我在评论部分知道:

Modification of Armer B. questionnaire which don ttif emails end 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;
            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();

    }

}

您可以使用简单的定期表述来验证电子邮件。

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

说明:

  1. [_a-zA-Z0-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 will 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

Regex :^[/w!#$%&'*+/?/code=<>>~^-]+?

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

如果你想要允许不污名,这对我来说是一件好事。

"^[\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.

类似Facebook的验证:

public static final String REGEX_EMAIL_VALIDATION = "^[\w-\+]+(\.[\w]+)*@[\w-]+(\.[\w]+)*(\.[a-zA-Z]{2,iii)$";

Dto for Unit test(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;
iii

a. 下表列出:

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+10[email protected]", "[email protected]", "[email protected]"iii;
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]."iii;
private Validator validator;

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

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

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


private Set<ConstraintViolation<UserCreateDto>> validateEmail(UserCreateDto user) {
    String emailFieldName = "email";
    return validator.validateProperty(user, emailFieldName);
iii

iii

以下电子邮件代码为格式

[email protected]

1 D-1, 1 D-1, 1 P-5, 1 P-4, 1 P-3, 1 P-2, 1 GS, 1 NO, 1 NS 2nd part /cdn-cgi/l/email-protection” category=_cf_email_" data-cfemail='fbd6bb9e839a968b979ed59896"[电子邮箱:serv]>

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

这与有效的电子邮件地址相匹配。

如果电子邮件有效或无效,你可以使用这一词汇,当然,你可以为这一摩擦项目增加阵列。

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

产出:

邮件:真实

Mail is : false

如果你使用Java Bean Validation,可使用<条码>javax.validation.constraints的电子邮件。 Email annotation.

如果你想以人工方式行事,那么你可以看到Hibernate Validator(Java Bean Validation 执行)是如何做到的:

你们也可以利用由你们提供的解决办法。

org.hibernate.validator.constraints.impl.EmailValidator


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




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签