Correo electrónico de Java regex

En primer lugar, sé que no se recomienda el uso de expresiones regulares para el correo electrónico, pero debo probarlo.

Tengo esta expresión regular:

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

En Java, hice esto:

 Pattern p = Pattern.compile("\\b[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[AZ]{2,4}\\b"); Matcher m = p.matcher("foobar@gmail.com"); if (m.find()) System.out.println("Correct!"); 

Sin embargo, la expresión regular falla independientemente de si el correo electrónico está bien formado o no. Un “buscar y reemplazar” dentro de Eclipse funciona bien con la misma expresión regular.

¿Alguna idea?

Gracias,

FWIW, aquí está el código de Java que usamos para validar las direcciones de correo electrónico. Los Regexp son muy similares:

 public static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[AZ]{2,6}$", Pattern.CASE_INSENSITIVE); public static boolean validate(String emailStr) { Matcher matcher = VALID_EMAIL_ADDRESS_REGEX .matcher(emailStr); return matcher.find(); } 

Funciona con bastante fiabilidad.

Aquí está la expresión regular de RFC822 adaptada para 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])*(?:[^()<>@,;:\\\\\".\\[\\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))*\"(?:(?:\\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", "user@.invalid.com", "Chuck Norris ", "webmaster@müller.de", "matteo@78.47.122.114" }; for (String email : emails) { System.out.println(email + " is " + (ptr.matcher(email).matches() ? "valid" : "invalid")); } 

Salida:

 "Fred Bloggs"@example.com is valid user@.invalid.com is invalid Chuck Norris  is valid webmaster@müller.de is valid matteo@78.47.122.114 is valid 

La expresión regular se toma de esta publicación: Mail :: RFC822 :: Address: validación de dirección basada en expresiones regulares . Los resultados deben coincidir con la versión en línea .

No lo hagas Nunca terminarás con una expresión válida.

Por ejemplo, estas son todas las direcciones de correo electrónico válidas:

 "Abc\@def"@example.com "Fred Bloggs"@example.com "Joe\\Blow"@example.com "Abc@def"@example.com customer/department=shipping@examp le.com $A12345@example.com !def!xyz%abc@example.com _somename@example.com matteo(this is a comment).corti@example.com root@[127.0.0.1] 

Solo por mencionar algunos problemas:

  • no considera las muchas formas de especificar un host (por ejemplo, por la dirección IP)
  • te pierdes personajes válidos
  • extrañas los nombres de dominio no ASCII

Antes incluso de comenzar, compruebe los RFC correspondientes

Eso es porque estás olvidando la insensibilidad del caso:

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

Esto coincide con su ejemplo, aunque ignora muchos correos electrónicos válidos.

Otra alternativa simple para validar el 99% de los correos electrónicos

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

¿El mecanizado está configurado en CASE_INSENSITIVE ?

Puede usar este método para validar la dirección de correo electrónico 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(); } } 

Formato de correo electrónico general (RE) que incluye también dominio como co.in, co.uk, com, outlook.com, etc.

Y la regla dice que:

  • Letras inglesas mayúsculas y minúsculas (az, AZ)
  • Dígitos 0 a 9
  • Caracteres ! # $% Y ‘* + – / =? ^ _ `{| } ~ Carácter.
  • (punto, punto, punto y aparte) siempre que no sea el primero o el último carácter, y siempre que no aparezca dos o más veces consecutivas.

     [a-zA-Z0-9]+[._a-zA-Z0-9!#$%&'*+-/=?^_`{|}~]*[a-zA-Z]*@[a-zA-Z0-9]{2,8}.[a-zA-Z.]{2,6} 

Esta es una expresión regular válida para validar correos electrónicos. Es totalmente compatible con RFC822 y acepta la dirección IP y los nombres de servidor (para fines de 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(); } 

Aquí hay algunos ejemplos de salida, cuando llama a isEmailValid(emailVariable) :

 john@somewhere.com // valid john.foo@somewhere.com // valid john.foo+label@somewhere.com // valid (with +label - Gmail accepts it!) john@192.168.1.10 // valid (with IP addresses) john+label@192.168.1.10 // valid (with +label and IP address) john.foo@someserver // valid (with no first domain level) JOHN.FOO@somewhere.com // valid (case insensitive) @someserver // invalid @someserver.com // invalid john@. // invalid .@somewhere.com // invalid 

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

Si quieres permitir caracteres que no sean latain, este funciona bastante bien para mí.

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

No permite las direcciones IP después del @, pero el correo electrónico más válido en xxx@xxx.TDL podría validarse con él. \p{L} valida UTF-Letters y \p{N} valida UTF-Numbers. Puede consultar este documento para obtener más información.

Regex para validación similar a Facebook:

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

Dto para pruebas unitarias (con 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; } 

Correos válidos / inválidos a continuación con pruebas de Unidad:

 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> 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> violations = validateEmail( new UserCreateDto().setEmail(email)); System.out.println("Email: " + email + ", violations: " + violations); Assert.assertTrue(!violations.isEmpty()); } ); } private Set> validateEmail(UserCreateDto user) { String emailFieldName = "email"; return validator.validateProperty(user, emailFieldName); } 

}

Pruebe el siguiente código para el correo electrónico es formato de

 jsmith@example.com 

1ra parte -jsmith 2da parte -@example.com

 1. In the 1 part it will allow 0-9,AZ,dot sign(.),underscore sign(_) 2. In the 2 part it will allow AZ, must be @ and . ^[a-zA-Z0-9_.]+@[a-zA-Z.]+?\.[a-zA-Z]{2,3}$ 

He probado esta regular expression continuación para puntos únicos y múltiples consecutivos en nombre de domain

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

y aquí están los ejemplos que se cumplieron por completo por encima de regex .

 End_user@live.com End.u@exm-tech.net enduser9876@gmail.in end_user@mywebsite.ac.in.gui Another984.User2@mail.edu.sg Another987_User5@mail.show.au Slow_User@example_domain.au.in iamthemostsimpleremailhere@example.com 

He intentado cubrir la máxima email id's validation utilizada comúnmente por esta regex ilustrada anteriormente pero que todavía funciona …

Si aún sabe que algunos email id's utilizados consecuentemente han quedado aquí, ¡por favor hágamelo saber en la sección de comentarios!

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

Esta es la expresión regular para hacer coincidir direcciones de correo electrónico válidas.

prueba esto

 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 }