Regular Expression to validate email provider string - Java

Asked

Viewed 35 times

-1

Hello! I’m trying to validate an email provider in Java using regular expression, but I’m not getting a result. I declared the variable for regex as string, but the suggestion is to use Boolean, only Boolean doesn’t meet what I need. I need to validate only the provider name after @. Could anyone help? Thank you so much!

String email = [email protected];
String filter = email.matches("@[a-z0-9]+\\.");
if(filter == "provedor1") {
    System.out.println("Usando o provedor1");  
} else {
    System.out.println("Usando o provedor2");  
}
  • About using regex to validate emails, there are a few things  here, here, here and here (this last link has some options at the end, just do not recommend the last regex).

1 answer

1

The important thing is to start with the documentation https://docs.oracle.com/en/java/, in that case the indexOf (java.lang.String) combined with the substring (java.lang.String), use the return of indexOf to validate whether the string came with @

Example:

String email = "[email protected]";
int pos = email.indexOf("@");

if (pos != -1) { // Se retornar -1 é um email invalido
    String provedor = email.substring(pos + 1);

    System.out.println(provedor);
} else {
    System.err.println("Email inválido");
}

Online example: https://ideone.com/vEInm8

Or you could use the split (java.lang.String), that internally uses regex, with the limit parameter to prevent that there is more than one @ it divides into unnecessary parts.

Use the

String email = "[email protected]";
String[] data = email.split("@", 2);

if (data.length > 1) { // se for "1" significa será um email invalido
    String provedor = data[1];

    System.out.println(provedor);
} else {
    System.err.println("Email inválido");
}

Online example: https://ideone.com/V3Azlv

Browser other questions tagged

You are not signed in. Login or sign up in order to post.