Checking for valid email address using regular expressions in Java


To verify whether a given input string is a valid e-mail id match it with the following is the regular expression to match an e-mail id −

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

Where,

  • ^ matches the starting of the sentence.

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

  • + indicates the repetition of the above-mentioned set of characters one or more times.

  • @ matches itself.

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

  • $ indicates 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.-]+$";
      //Matching the given phone number with 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:
example.samplemail@gmail.com
Given email-id is valid

Output 2

Enter your Email:
sample?examplemail@gmail.com
Given email-id is not valid

Example 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("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.-]+$";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(phone);
      //Verifying whether given phone number is valid
      if(matcher.matches()) {
         System.out.println("Given email id is valid");
      } else {
         System.out.println("Given email id is not valid");
      }
   }
}

Output 1

Enter your name:
vagdevi
Enter your email id:
sample.123@gmail.com
Given email id is valid

Output 2

Enter your name:
raja
Enter your email id:
raja$test@gmail.com
Given email id is not valid

Start learning Java with our Java tutorial from scratch.

Updated on: 19-Feb-2024

64K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements