Java regular expression program to validate an email including blank field valid as well



Following regular expression matches given e-mail id including the blank input −

^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})?$

Where,

  • ^ matches the starting of the sentence.

  • [a-zA-Z0-9._%+-] matches one character from 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 English alphabet (both cases), digits, "." and "-" after the @ symbol

  • \.[a-zA-Z]{2,6} two to 6 letter for email domain after "."

  • $ indicates the end of the sentence

Example 1

 Live Demo

import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SampleTest {    public static void main( String args[] ) {       String regex = "^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})?$";       //Reading input from user       Scanner sc = new Scanner(System.in);       System.out.println("Enter your name: ");       String name = sc.nextLine();       System.out.println("Enter your e-mail: ");       String e_mail = sc.nextLine();       System.out.println("Enter your age: ");       int age = sc.nextInt();       //Instantiating the Pattern class       Pattern pattern = Pattern.compile(regex);       //Instantiating the Matcher class       Matcher matcher = pattern.matcher(e_mail);       //verifying whether a match occurred       if(matcher.find()) {          System.out.println("e-mail value accepted");       } else {          System.out.println("e-mail not value accepted");       }    } }

Output1

Enter your name: krishna Enter your e-mail: Enter your age: 20 e-mail value accepted

Output 2

Enter your name: Rajeev Enter your e-mail: rajeev.123@gmail.com Enter your age: 25 e-mail value accepted

Example 2

 Live Demo

import java.util.Scanner; public class Example {    public static void main(String args[]) {       //Reading String from user       System.out.println("Enter email address: ");       Scanner sc = new Scanner(System.in);       String e_mail = sc.nextLine();       //Regular expression       String regex = "^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})?$";       boolean result = e_mail.matches(regex);       if(result) {          System.out.println("Valid match");       } else {          System.out.println("Invalid match");       }    } }

Output 1

Enter email address: rajeev.123@gmail.com Valid match

Output 2

Enter email address: Valid match
Updated on: 2020-01-10T11:39:06+05:30

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements