English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Come verificare un indirizzo email valido utilizzando la regex Java?

To verify whether the given input string is a valid email ID, please use the following regular expression to match the given input string to match the email ID-

"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$"

Where,

  • ^ matches the beginning of the sentence.

  • [a-zA-Z0-9 + _.-] matches a character from the English alphabet (two cases), the number "+", "_", "." before the "@" symbol.

  • + indicates one or more repetitions of the preceding character set.

  • @ matches itself.

  • [a-zA-Z0-9.-] matches a character from the English alphabet (two cases), the number "." after the "@" symbol.

  • $ represents the end of the sentence.

Esempio

import java.util.Scanner;
public class ValidatingEmail {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your Email: ");
      String phone = sc.next();
      String regex = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$";
      //Match the given number with the regular expression
      boolean result = phone.matches(regex);
      if(result) {
         System.out.println("Given email-id is valid");
      } else {
         System.out.println("Given email-id is not valid");
      }
   }
}

Output 1

Enter your Email:
[email protected]
Given email-id is valid

Output 2

Enter your Email:
[email protected]
Given email-id is not valid

Esempio 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Inserisci il tuo nome:");
      String name = sc.nextLine();
      System.out.println("Inserisci il tuo email ID:");
      String phone = sc.next();
      //Espressione regolare accettata per l'email ID valido
      String regex = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$";
      //Crea un oggetto Pattern
      Pattern pattern = Pattern.compile(regex);
      //Crea un oggetto Matcher
      Matcher matcher = pattern.matcher(phone);
      //Verifica se il numero fornito è valido
      if(matcher.matches()) {
         System.out.println("L'email ID fornito è valida");
      } else {
         System.out.println("L'email ID fornito non è valida");
      }
   }
}

Output 1

Inserisci il tuo nome:
vagdevi
Inserisci il tuo email ID:
[email protected]
L'email ID fornito è valida

Output 2

Inserisci il tuo nome:
raja
Inserisci il tuo email ID:
[email protected]
L'email ID fornito non è valida
Ti potrebbe interessare