Tutorialspoint examples

Learn java tutorial with examples for beginners online

java regex pattern validate email


Regular expressions

Regular expressions represents a sequence of symbols and characters expressing a string or pattern to be searched for within a longer piece of text. The abbreviation for regular expression is regex. In programming regular expressions are mainly used to define constraint on strings like password, email validation.

^[_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.tutorialspointexamples;
 
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("jaisingh70@yahoo.com"); 
		values.add("jaipannu99@gmail.com"); 
		values.add("jaipannu99@.com");
		values.add("jaipannu99@gmail.com.a");
 
		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
Download tutorialspointexamples Android App
Copyright © 2018 Tutorialspoint examples DMCA.com Protection Status