Comment valider une adresse e-mail avec une expression régulière
Modèle d'expression régulière d'e-mail
^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)* @[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$;
La description
^ #start of the line [_A-Za-z0-9-\\+]+ # must start with string in the bracket [ ], must contains one or more (+) ( # start of group #1 \\.[_A-Za-z0-9-]+ # follow by a dot "." and string in the bracket [ ], must contains one or more (+) )* # end of group #1, this group is optional (*) @ # must contains a "@" symbol [A-Za-z0-9-]+ # follow by string in the bracket [ ], must contains one or more (+) ( # start of group #2 - first level TLD checking \\.[A-Za-z0-9]+ # follow by a dot "." and string in the bracket [ ], must contains one or more (+) )* # end of group #2, this group is optional (*) ( # start of group #3 - second level TLD checking \\.[A-Za-z]{2,} # follow by a dot "." and string in the bracket [ ], with minimum length of 2 ) # end of group #3 $ #end of the line
La combinaison signifie que l'adresse e-mail doit commencer par «_A-Za-z0-9 - \ +», facultative suivie de «. [_ A-Za-z0-9-]» et se terminer par un symbole «@». Le nom de domaine de l'e-mail doit commencer par "A-Za-z0-9-", suivi du premier niveau Tld (.com, .net) ". [A-Za-z0-9]" et facultatif suivi d'un deuxième niveau Tld (.com.au, .com.my) "\. [A-Za-z] \ {2,}", où le Tld de deuxième niveau doit commencer par un point "." et la longueur doit être égale ou supérieure à 2 caractères.
1. Exemple d'expression régulière Java
Voici un exemple Java pour vous montrer comment utiliser regex pour valider une adresse e-mail.
EmailValidator.java
package com.example.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; 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(); } }
2. Courriels valides
3. E-mails non valides
1. exemple - doit contenir le symbole «@»
2. exemple @ .com.my - tld ne peut pas commencer par le point «.»
3. [email protected] - «.a» n'est pas un tld valide, le dernier tld doit contenir au moins deux caractères
4. example123 @ .com - tld ne peut pas commencer par le point «.»
5. example123 @ .com.com - tld ne peut pas commencer par le point «.»
6. .[email protected] - Le premier caractère de l'e-mail ne peut pas commencer par le point "."
7. exemple ()@gmail.com – email’s is only allow character, digit,
underscore and dash
8. example@%.com - le tld de l’e-mail n’autorise que le caractère et le chiffre
9. [email protected] – double dots “.” are not allow
10. [email protected] – email’s last character can not end with dot “.”
11. example@[email protected] – double “@” is not allow
12. [email protected].1a -email’s tld which has two characters can not contains digit
4. Test de l'unité
Voici un test unitaire utilisanttestNG.
EmailValidatorTest.java
package com.example.regex; import org.testng.Assert; import org.testng.annotations.*; /** * Email validator Testing * * @author example * */ public class EmailValidatorTest { private EmailValidator emailValidator; @BeforeClass public void initData() { emailValidator = new EmailValidator(); } @DataProvider public Object[][] ValidEmailProvider() { return new Object[][] { { new String[] { "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]" } } }; } @DataProvider public Object[][] InvalidEmailProvider() { return new Object[][] { { new String[] { "example", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "example()*@gmail.com", "example@%*.com", "[email protected]", "[email protected]", "example@[email protected]", "[email protected]" } } }; } @Test(dataProvider = "ValidEmailProvider") public void ValidEmailTest(String[] Email) { for (String temp : Email) { boolean valid = emailValidator.validate(temp); System.out.println("Email is valid : " + temp + " , " + valid); Assert.assertEquals(valid, true); } } @Test(dataProvider = "InvalidEmailProvider", dependsOnMethods = "ValidEmailTest") public void InValidEmailTest(String[] Email) { for (String temp : Email) { boolean valid = emailValidator.validate(temp); System.out.println("Email is valid : " + temp + " , " + valid); Assert.assertEquals(valid, false); } } }
Voici le résultat du test unitaire.
Email is valid : [email protected] , true Email is valid : [email protected] , true Email is valid : [email protected] , true Email is valid : [email protected] , true Email is valid : [email protected] , true Email is valid : [email protected] , true Email is valid : [email protected] , true Email is valid : [email protected] , true Email is valid : [email protected] , true Email is valid : [email protected] , true Email is valid : example , false Email is valid : [email protected] , false Email is valid : [email protected] , false Email is valid : [email protected] , false Email is valid : [email protected] , false Email is valid : [email protected] , false Email is valid : example()*@gmail.com , false Email is valid : example@%*.com , false Email is valid : [email protected] , false Email is valid : [email protected] , false Email is valid : example@[email protected] , false Email is valid : [email protected] , false PASSED: ValidEmailTest([Ljava.lang.String;@15f48262) PASSED: InValidEmailTest([Ljava.lang.String;@789934d4) =============================================== Default test Tests run: 2, Failures: 0, Skips: 0 ===============================================