- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to validate an email address format in Java
Problem Description
How to validate an email address format?
Solution
Following example demonstrates how to validate e-mail address using matches() method of String class.
public class Main {
public static void main(String[] args) {
String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
String email1 = "user@domain.com";
Boolean b = email1.matches(EMAIL_REGEX);
System.out.println("is e-mail: "+email1+" :Valid = " + b);
String email2 = "user^domain.co.in";
b = email2.matches(EMAIL_REGEX);
System.out.println("is e-mail: "+email2+" :Valid = " + b);
}
}
Result
The above code sample will produce the following result.
is e-mail: user@domain.com :Valid = true is e-mail: user^domain.co.in :Valid = false
The following is an example to validate an email address format.
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
List emails = new ArrayList();
emails.add("sairamkrishna@tutorialspoint.com");
emails.add("kittuprasad700@gmail.com");
emails.add("sairamkrishna_mammahe%google-india.com");
emails.add("sairam.krishna@gmail-indai.com");
emails.add("sai#@youtube.co.in");
emails.add("kittu@domaincom");
emails.add("kittu#gmail.com");
emails.add("@pindom.com");
String regex = "^(.+)@(.+)$";
Pattern pattern = Pattern.compile(regex);
for (Object email : emails) {
Matcher matcher = pattern.matcher((CharSequence) email);
System.out.println(email + " : " + matcher.matches());
}
}
}
The above code sample will produce the following result.
sairamkrishna@tutorialspoint.com : true kittuprasad700@gmail.com : true sairamkrishna_mammahe%google-india.com : false sairam.krishna@gmail-indai.com : true sai#@youtube.co.in : true kittu@domaincom : true kittu#gmail.com : false @pindom.com : false
java_regular_exp.htm
Advertisements