How to validate email address with regular expression

Email Regular Expression Pattern


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

Description


^			#start of the line
  [_A-Za-z0-9-\\+]+	#  must start with string in the bracket [ ], must contains one or more (+)
  (			#   start of group #1
    \\.[_A-Za-z0-9-]+	#     follow by a dot "." and string in the bracket [ ], must contains one or more (+)
  )*			#   end of group #1, this group is optional (*)
    @			#     must contains a "@" symbol
     [A-Za-z0-9-]+      #       follow by string in the bracket [ ], must contains one or more (+)
      (			#         start of group #2 - first level TLD checking
       \\.[A-Za-z0-9]+  #           follow by a dot "." and string in the bracket [ ], must contains one or more (+)
      )*		#         end of group #2, this group is optional (*)
      (			#         start of group #3 - second level TLD checking
       \\.[A-Za-z]{2,}  #           follow by a dot "." and string in the bracket [ ], with minimum length of 2
      )			#         end of group #3
$			#end of the line

The combination means, email address 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.

1. Java Regular Expression Example

Here’s a Java example to show you how to use regex to validate email address.

EmailValidator.java

package com.mkyong.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailValidator {

	private Pattern pattern;
	private Matcher matcher;

	private static final String EMAIL_PATTERN = 
		"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
		+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

	public EmailValidator() {
		pattern = Pattern.compile(EMAIL_PATTERN);
	}

	/**
	 * Validate hex with regular expression
	 * 
	 * @param hex
	 *            hex for validation
	 * @return true valid hex, false invalid hex
	 */
	public boolean validate(final String hex) {

		matcher = pattern.matcher(hex);
		return matcher.matches();

	}
}

2. Valid Emails

1. mkyong@yahoo.com, mkyong-100@yahoo.com, mkyong.100@yahoo.com
2. mkyong111@mkyong.com, mkyong-100@mkyong.net, mkyong.100@mkyong.com.au
3. mkyong@1.com, mkyong@gmail.com.com
4. mkyong+100@gmail.com, mkyong-100@yahoo-test.com

3. Invalid Emails

1. mkyong – must contains “@” symbol
2. mkyong@.com.my – tld can not start with dot “.”
3. mkyong123@gmail.a – “.a” is not a valid tld, last tld must contains at least two characters
4. mkyong123@.com – tld can not start with dot “.”
5. mkyong123@.com.com – tld can not start with dot “.”
6. .mkyong@mkyong.com – email’s first character can not start with dot “.”
7. mkyong()*@gmail.com – email’s is only allow character, digit, underscore and dash
8. mkyong@%*.com – email’s tld is only allow character and digit
9. mkyong..2002@gmail.com – double dots “.” are not allow
10. mkyong.@gmail.com – email’s last character can not end with dot “.”
11. mkyong@mkyong@gmail.com – double “@” is not allow
12. mkyong@gmail.com.1a -email’s tld which has two characters can not contains digit

4. Unit Test

Here’s a unit test using testNG.

EmailValidatorTest.java

package com.mkyong.regex;

import org.testng.Assert;
import org.testng.annotations.*;

/**
 * Email validator Testing
 * 
 * @author mkyong
 * 
 */
public class EmailValidatorTest {

	private EmailValidator emailValidator;

	@BeforeClass
	public void initData() {
		emailValidator = new EmailValidator();
	}

	@DataProvider
	public Object[][] ValidEmailProvider() {
		return new Object[][] { { new String[] { "mkyong@yahoo.com",
			"mkyong-100@yahoo.com", "mkyong.100@yahoo.com",
			"mkyong111@mkyong.com", "mkyong-100@mkyong.net",
			"mkyong.100@mkyong.com.au", "mkyong@1.com",
			"mkyong@gmail.com.com", "mkyong+100@gmail.com",
			"mkyong-100@yahoo-test.com" } } };
	}

	@DataProvider
	public Object[][] InvalidEmailProvider() {
		return new Object[][] { { new String[] { "mkyong", "mkyong@.com.my",
			"mkyong123@gmail.a", "mkyong123@.com", "mkyong123@.com.com",
			".mkyong@mkyong.com", "mkyong()*@gmail.com", "mkyong@%*.com",
			"mkyong..2002@gmail.com", "mkyong.@gmail.com",
			"mkyong@mkyong@gmail.com", "mkyong@gmail.com.1a" } } };
	}

	@Test(dataProvider = "ValidEmailProvider")
	public void ValidEmailTest(String[] Email) {

		for (String temp : Email) {
			boolean valid = emailValidator.validate(temp);
			System.out.println("Email is valid : " + temp + " , " + valid);
			Assert.assertEquals(valid, true);
		}

	}

	@Test(dataProvider = "InvalidEmailProvider", dependsOnMethods = "ValidEmailTest")
	public void InValidEmailTest(String[] Email) {

		for (String temp : Email) {
			boolean valid = emailValidator.validate(temp);
			System.out.println("Email is valid : " + temp + " , " + valid);
			Assert.assertEquals(valid, false);
		}
	}
}

Here’s the unit test result.


Email is valid : mkyong@yahoo.com , true
Email is valid : mkyong-100@yahoo.com , true
Email is valid : mkyong.100@yahoo.com , true
Email is valid : mkyong111@mkyong.com , true
Email is valid : mkyong-100@mkyong.net , true
Email is valid : mkyong.100@mkyong.com.au , true
Email is valid : mkyong@1.com , true
Email is valid : mkyong@gmail.com.com , true
Email is valid : mkyong+100@gmail.com , true
Email is valid : mkyong-100@yahoo-test.com , true
Email is valid : mkyong , false
Email is valid : mkyong@.com.my , false
Email is valid : mkyong123@gmail.a , false
Email is valid : mkyong123@.com , false
Email is valid : mkyong123@.com.com , false
Email is valid : .mkyong@mkyong.com , false
Email is valid : mkyong()*@gmail.com , false
Email is valid : mkyong@%*.com , false
Email is valid : mkyong..2002@gmail.com , false
Email is valid : mkyong.@gmail.com , false
Email is valid : mkyong@mkyong@gmail.com , false
Email is valid : mkyong@gmail.com.1a , false
PASSED: ValidEmailTest([Ljava.lang.String;@15f48262)
PASSED: InValidEmailTest([Ljava.lang.String;@789934d4)

===============================================
    Default test
    Tests run: 2, Failures: 0, Skips: 0
===============================================

References

  1. http://en.wikipedia.org/wiki/E-mail_address
  2. http://tools.ietf.org/html/rfc2822#section-3.4.1

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
74 Comment threads
28 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
80 Comment authors
Animesh PantSUDHANSU SEKHAR NAYAKNawazLKrDavy Jones Recent comment authors
newest oldest most voted
Douglas De Rizzo Meneghetti
Guest
Douglas De Rizzo Meneghetti

I tried this code with “email@goes_here.com” and it was deemed invalid. I guess it’s because of the underscore.

Stefan
Guest
Stefan

It is not possible to validate an emailadress with a regular expression in the general case. The only way to validate an emailadress is to send a mail and wait for a response. The best you can do with a regexp is to validate that the syntax is correct as defined in rfc2822 but the regexp that covers that is about one page long and much more complicated than your example. To make matters worse only a few syntactically correct emailadresses actually have someone or something that receives mail on it. My advice is that if you have to check… Read more »

JoshDM
Guest
JoshDM

You are returning false on the valid case:

mykong+100@gmail.com

Gmail parses e-mails sent to it with a + character; mykong@gmail.com will receive the above e-mail, but it will be filtered as a “100” e-mail.

This is useful functionality when submitting valid e-mails to potential spam processes; for example a business promotion. You can see if your e-mail is getting re-sold. Unfortunately for the consumer, many validators disallow the + character.

Christian Harms
Guest
Christian Harms

I found errors in the local, domain and top level part: ———– The local part is not limited to characters (c&p from your links): ———– * Uppercase and lowercase English letters (a-z, A-Z) * Digits 0 to 9 * Characters ! # $ % & ‘ * + – / = ? ^ _ ` { | } ~ * Character . ———– The Domain name is limited to 63 characters, the sum of domain name part to 256! ———– The Top-Level-Domain can limited by {2,5} (was {2,}) unless the asian idna-coded top level domains arraived the wild… ———–

trackback
10 Java Regular Expression Examples You Should Know | Regular Expressions

[…] ==> See the explanation and example here […]

poltava
Guest
poltava

Such e-mail as test@mky-ong.com will fail validation.

Yashvin
Guest
Yashvin

Hi everyone!

mkyoug, thnks very much for this expression.
Learning to use regex and to satisfy the + and – characters, I slightly modified your code.
here is the final regex which seem to work correctly

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

Cheers everyone,
Yashvin
From Mauritius.

Brijesh Kumar(WeboniseLab)
Guest
Brijesh Kumar(WeboniseLab)

package proj2; import java.util.regex.*; import java.io.*; public class SecondStage { public static void main(String[] aArgs) throws IOException { FileWriter fValid= new FileWriter("/home/webonise/valid.txt"); FileWriter fInvalid= new FileWriter("/home/webonise/invalid.txt"); String strRe=new String("^([a-z0-9._%+-])+@[a-z0-9.-]+\\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|vsnl|yahoo|gmail|info|mobi|name|aero|asia|jobs|museum)+$"); Pattern p = Pattern.compile(strRe,Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.MULTILINE); try { BufferedReader in = new BufferedReader(new FileReader("/home/webonise/users.csv")); String str2=";"; String str1="\""; String str; String[] x=new String[2]; while ((str = in.readLine()) != null) { String trial[]; trial= str.split(str2); try { for(int i=0;i<trial.length;i++) { x[i]=trial[i].replaceAll(str1,""); x[i]=x[i].replaceAll(" ",""); } Matcher m = p.matcher(x[1]); if(m.matches()) { fValid.write(str+"\n"); } else { fInvalid.write(str+"\n"); } } catch(Exception e) { e.printStackTrace(); } } fValid.close(); fInvalid.close(); in.close(); } catch (IOException e)… Read more »

trackback
Custom validator in JSF 2.0

[…] Note For detail explanation about the above regular expression pattern, please refer to this “Validate E-mail with Java regular expression” […]

Sefi
Guest
Sefi

In spite of fairly simple being of the java.util.regex I am still struggling to make it work, but having read through this article along with the codes in the comment section I will give it a go again tonight…thnaks for the code MKYong

vasili
Guest
vasili

Final version, we use, covering emails, we received so far, is:

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

If somebody will get emails which can’t be fit in this regexp – please post in this thread.

trackback
Spring EL regular expression example

[…] Source Code Download It – Spring3-EL-Regular-Expression-Example.zip (6 KB)ReferencesEmail regular expression exampleSpring EL ternary operator (if-then-else) example […]

tripleee
Guest
tripleee

Turns out this somehow ended up being contributed to Struts. You might be interested in seeing how it turned out; https://issues.apache.org/jira/browse/WW-2805

multi
Guest
multi

Great stuff, thanks! Really helped me.

abhilash
Guest
abhilash

Thanks a lot…. 🙂

Sireesha
Guest
Sireesha

Hi,

This validation works fine but it is not validating if i give like this.

Example:abc@software.co.zasdsjjh

Please anybody give solution for this.

Thanks
Sireesha

hari krishna
Guest
hari krishna

i need the code to be changed so that it should not accept .com.com, the repeated things
Please help me.

lars
Guest
lars

According to http://tools.ietf.org/html/rfc3696#page-5 the following characters are legal in the local part of an E-Mail address:

! # $ % & ‘ * + – / = ? ^ _ ` . { | } ~

So the resulting regex would be:

	private static final String	EMAIL_PATTERN	= "^[!#-'\\*\\+\\-/0-9=\\?A-Z\\^_`a-z{-~]+(\\.[!#-'\\*\\+\\-/0-9=\\?A-Z\\^_`a-z{-~]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
trackback
How to validate email address with regular expression | Chinasb's Blog

[…] ?????http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/ Share this on: Mixx Delicious Digg Facebook Twitter Regular Expression […]

trackback
Validating email addresses with Bean Validation « jinahya

[…] How to validate email address with regular expression […]

JSupport
Guest
JSupport

Use Java mail API to validate email address, which is the easiest way to validate email address in java. You will be find the answer from here How To Validate Email Address using Java Mail API

dro0x
Guest
dro0x

Hi, your regex works well except for a little oversight in the domain check. It doesn’t allow for hyphens. For example the following email will not validate: person@blah-blah.com

Varadharajan
Guest
Varadharajan

Hi,

I m trying to write my own reg ex after referring to this tutorial.
I wrote the following reg exp for validating the email id.
^((?=\\w).)+@([a-z]*).(com)
The above works for all the inputs that you have given here.
But fails for this example
mkyong-100@yahoo.com
So i changed the regex so as to include “-” in the validation, but it fails.
^((?=\\w)(?=\\-).)+@([a-z]*).(com)
Can you please tell me what has went wrong.

Thanks

trackback
Handy Javascript code segments | Blog | Personal Website of Clivant Yeo Chai Heng | techcoil.com

[…] Regular expression pattern taken from mkyong.com. […]

Danish
Guest
Danish

Thanx buddy it worked fine for me

Padmanabhan
Guest
Padmanabhan

Wonderful article. Just need one help. i want to restrict hyphen(-) and underscore(_) also from repeating more than two consecutive times like dot(.) please guide me

David Domincki
Guest
David Domincki

Hi my friend! I want to say that this post is amazing, nice written and come with approximately all significant infos. I’d like to peer extra posts like this.

trackback
Reguläre AusdrĂĽcke (RegEx) « Michael Braukhoff

[…] Beispiel habe ich mir hier […]

Mithun
Guest
Mithun

Though a dumb question.

I would like to know how the caret(^) at the start and ($) at the end affects the regex?

Thanks

John Ortiz
Guest
John Ortiz

Hi mkyong,

Can you suggest me a good book to learn write RegEx from scratch? Thanks in advance.

Regards,
John Ortiz