java regex pattern validate email

Regular expression email pattern

^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$

This regular expression refers to a pattern which must start with “_A-Za-z0-9-\+” , optional follow by “.[_A-Za-z0-9-]”, and end with a “@” symbol. The email’s domain name must start with “A-Za-z0-9-“, follow by first level Tld (.com, .net) “.[A-Za-z0-9]” and optional follow by a second level Tld (.com.au, .com.my) “\.[A-Za-z]{2,}”, where second level Tld must start with a dot “.” and length must equal or more than 2 characters.

Example

package com.w3schools;
 
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexTest {
	private static final String PATTERN = 
			"^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@"
			+ "[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$";
	public static void main(String args[]){ 
		List<String> values = new ArrayList<String>();	
		values.add("[email protected]"); 
		values.add("[email protected]"); 
		values.add("[email protected]");
		values.add("[email protected]");
 
		Pattern pattern = Pattern.compile(PATTERN);
		for (String value : values){
		  Matcher matcher = pattern.matcher(value);
		  if(matcher.matches()){
			  System.out.println("Email "+ value +" is valid");
		  }else{
			  System.out.println("Email "+ value +" is invalid");
		  }		  
		}
	}
}

Output

Email jaisingh70@yahoo.com is valid
Email jaipannu99@gmail.com is valid
Email jaipannu99@.com is invalid
Email jaipannu99@gmail.com.a is invalid