
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check 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: [email protected] Given email-id is valid
Output 2
Enter your Email: [email protected] 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: [email protected] Given email id is valid
Output 2
Enter your name: raja Enter your email id: [email protected] Given email id is not valid
Start learning Java with our Java tutorial from scratch.
Advertisements