Validate email in JAVA memory

Asked

Viewed 185 times

0

In java, how do I check if the String the user typed has the character "@" or ends with ". com" or ". br" to validate the email in memory ?

  • 1

    The linked question is with javascript, but just use the class java.util.regex.Pattern that can be easily adapted to java.

  • 1

    Still 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). For the use of regex specifically in Java, I suggest this tutorial

  • You can use the regex \w+(@)\w+(.)\w+, which verifies the existence of a "@" and a "." and characters between them.

1 answer

2

To know if the string has the character @, you can use the contains:

String teste = "abc@s";
if (teste.contains("@")) {
    System.out.println("existe o caractere @ na string");
} else {
    System.out.println("não existe o caractere @ na string");
}

To know if the string ends with .com or .br you can use a substring:

String teste = "teste.com";
if (teste.substring(teste.length() - 4, teste.length()).equals(".com")) {
     System.out.println("a string acaba com .com");
} else {
     System.out.println("a string nao acaba com .com");
}

if (teste.substring(teste.length() - 3, teste.length()).equals(".br")) {
    System.out.println("a string acaba com .br");
} else {
    System.out.println("a string não acaba com .br");
}
  • 1

    Instead of substring, it is also possible to use endsWith

Browser other questions tagged

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