E-mail Java regex


Tout d'Abord, je sais que l'utilisation de regex pour le courrier électronique n'est pas recommandée, mais je dois la tester.

J'ai cette expression régulière:

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

En Java, j'ai fait ceci:

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

Cependant, l'expression régulière échoue, que l'e-mail soit formé ou non. Un "rechercher et remplacer" dans Eclipse fonctionne bien avec la même expression régulière.

Une idée?

Merci,

Author: Tu Hoang, 2011-11-21

16 answers

FWIW, voici le code Java que nous utilisons pour valider les adresses e-mail. Les expressions rationnelles sont très similaires:

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

Fonctionne de manière assez fiable.

 169
Author: Jason Buberel, 2011-11-20 21:04:06

Voici une expression régulière compatible RFC822 adaptée pour 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)?[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\\]]))|\"(?:[^\\\"\\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"));
}

Sortie:

"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

L'expression régulière est tirée de cet article: Mail::RFC822::Address: regexp-based address validation. Les résultats doivent coïncider avec version en ligne.

 158
Author: ejboy, 2013-03-11 13:10:37

Ne le faites pas. Vous ne finirez jamais avec une expression valide.

Par exemple ce sont toutes des adresses e-mail valides:

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

Juste pour mentionner quelques problèmes:

  • vous ne considérez pas les nombreuses formes de spécification d'un hôte (par exemple, par l'adresse IP)
  • vous manquez des caractères valides
  • vous manquez des noms de domaine non ASCII

Avant même de commencer, vérifiez les RFC correspondants

 11
Author: Matteo, 2011-11-20 21:16:37

C'est parce que vous oubliez l'insensibilité à la casse:

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

Cela correspond à votre exemple, bien qu'il ignore de nombreux e-mails valides.

 6
Author: FailedDev, 2011-11-20 21:16:03

Une autre alternative simple pour valider 99% des emails

public static final String EMAIL_VERIFICATION = "^([\\w-\\.]+){1,64}@([\\w&&[^_]]+){2,255}.[a-z]{2,}$";
 3
Author: Armer B., 2017-06-21 10:51:16

Maching est-il défini sur CASE_INSENSITIVE?

 2
Author: Xaerxess, 2011-11-20 21:09:55

Vous pouvez utiliser cette méthode pour valider l'adresse e-mail en 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();

    }
}
 1
Author: Chanaka udaya, 2013-09-06 14:55:30

Format général d'email (RE) qui incluent également le domaine comme co.in, co.uk, com, outlook.com etc.

Et la règle dit que :

  • Lettres anglaises majuscules et minuscules (a-z, A-Z)
  • Chiffres 0 à 9
  • Caractères ! # $ % & ' * + - / = ? ^ _ ` { | } ~ Caractère.
  • (point, point, point complet) à condition que ce ne soit pas le premier ou le dernier caractère, et à condition également qu'il ne semble pas deux ou plus fois consécutivement.

    [a-zA-Z0-9]+[._a-zA-Z0-9!#$%&'*+-/=?^_`{|}~]*[a-zA-Z]*@[a-zA-Z0-9]{2,8}.[a-zA-Z.]{2,6}
    
 1
Author: Hitesh Kalwani, 2017-01-27 11:11:15

Il s'agit d'une expression régulière valide pour valider les e-mails. Il est totalement conforme à la norme RFC822 et accepte les adresses IP et les noms de serveur (à des fins intranet).

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

Voici quelques exemples de sortie, lorsque vous appelez 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
 1
Author: shimatai, 2018-02-10 21:01:17

Expression régulière : ^[\\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();
    }
 0
Author: Neo, 2015-09-26 10:26:17

Si vous voulez autoriser les caractères non latains, celui-ci fonctionne assez bien pour moi.

"^[\\p{L}\\p{N}\\._%+-]+@[\\p{L}\\p{N}\\.\\-]+\\.[\\p{L}]{2,}$"

Il n'autorise pas les IP après le @ mais le courrier électronique le plus valide dans le from of [email protected] pourrait être validé avec lui. \p{L} valide les lettres UTF et \p{N} valide les nombres UTF. Vous pouvez consulter ce document pour plus d'informations.

 0
Author: Nabil A., 2015-11-16 12:57:30

Regex pour la validation Facebook-like:

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

Dto pour les tests unitaires (avec 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;
}

E-mails valides/invalides ci-dessous avec des tests unitaires:

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

}

 0
Author: Alex Efimov, 2017-11-08 13:36:16

Essayez le code ci-dessous pour l'email est le format de

[email protected]

1ère partie -jsmith 2 [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}$
 0
Author: charan, 2018-03-14 14:25:49

J'ai testé ce ci-dessous regular expression pour un seul ou de plusieurs points consécutifs dans domain nom

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

Et voici les exemples qui ont été complètement remplis par ci-dessus regex.

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

J'ai essayé de couvrir maximum couramment utilisé email id's validation par ce ci-dessus illustré regex et pourtant de travail...

Si vous savez encore que certains email id's utilisés de manière conséquente étaient partis ici, veuillez me le faire savoir dans la section des commentaires!

 0
Author: ArifMustafa, 2018-05-02 02:59:17
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");

Il s'agit de l'expression régulière pour faire correspondre les adresses e-mail valides.

 0
Author: prakhar9293, 2018-07-05 16:17:15

Essayez ceci

String regex = "^[\\p{L}\\p{N}\\._%+-]+@[\\p{L}\\p{N}\\.\\-]+\\.[\\p{L}]{2,}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(Email);
if (matcher.matches()) {
   //your Logic
}
 -1
Author: Sohil Ahmed, 2017-10-04 12:11:45