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

Use Java regular expressions to check valid email addresses

To verify whether the given input string is a valid email ID, 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 + _.-[a] matches a character from the English alphabet (two cases), a number ", +", "_", ".", the "-" before the @ symbol.-"

  • +Represents repeating the above character set one or more times.

  • @ matches itself.

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

  • $ represents the end of the sentence.

Example

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

Output1

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

Output2

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

Example2

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("Enter your name:");
      String name = sc.nextLine();
      System.out.println("Enter your email id:");
      String phone = sc.next();
      //Regular expression to accept valid email ID
      String regex = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$";
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Create a Matcher object
      Matcher matcher = pattern.matcher(phone);
      //Verify if the given number is valid
      if(matcher.matches()) {
         System.out.println("Given email id is valid");
      } else {
         System.out.println("Given email id is not valid");
      }
   }
}

Output1

Enter your name:
vagdevi
Enter your email id:
[email protected]
Given email id is valid

Output2

Enter your name:
raja
Enter your email id:
[email protected]
Given email id is not valid
You May Also Like