How to validate multiple email addresses with regular expression in Java

In this example I have demonstrated the use of the regular expressions in Java programming language to do a validation of the email address. The email address might be just one or multiples selected by a semi colon or a comma. I also have presented numerous test cases of the email addresses and then have finally provided the output of running the program, as usual.

package com.icodejava.tools;

/**
 * @author Kushal Paudyal
 * Last Modified on 2011/05/11
 * 
 * This class demonstrates the use of regular expressions to validate multiple email
 * addresses. Several test examples of the email addresses are also provided.
 * 
 * www.icodejava.com
 */
import java.util.regex.Pattern;

public class RegexMultipleEmailAddressValidation {
	/**
	 * Define a regular expression to validate multiple email addresses.
	 * I think the following expression is more complex that it has to be.
	 * We can think of refactoring it at some later point. But it works 
	 * just fine right now.
	 */
	public static String regex = 
		"(([A-Za-z0-9_\\-\\.])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,4}))(((;|,|; | ;| ; | , | ,){1}"
		+"([A-Za-z0-9_\\-\\.])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,4}))*)";

	public static void main(String[] args) {
		/**
		 * Validate various email addresses
		 */
		isValid("billgates@badmicrosoft.com");
		isValid("billgates@nation.wide.com");
		isValid("123@badmicrosoft.com");
		isValid("'billgates@badmicrosoft.com'");
		isValid("billgates@badmicrosoft.123");
		isValid("abc.def@badmicrosoft.com");
		isValid("abc.\\def@badmicrosoft.com");
		isValid("abc_def@badmicrosoft.com");
		isValid("abc_def.@badmicrosoft.com");
		isValid("abc_def-@badmicrosoft.com");
		isValid("^billgates@badmicrosoft.com");
		isValid("billgates@badmicrosoft.com;noreply@badmicrosoft.com");
		isValid("billgates@badmicrosoft.com,noreply@badmicrosoft.com");
		isValid("billgates@badmicrosoft.com;;noreply@badmicrosoft.com");
		isValid("billgates@badmicrosoft.com;,noreply@badmicrosoft.com");
		isValid("billgates@badmicrosoft.com; noreply@badmicrosoft.com");
		isValid("billgates@badmicrosoft.com ; noreply@badmicrosoft.com");
		isValid("billgates@badmicrosoft.com , noreply@badmicrosoft.com");
		isValid("billgates@badmicrosoft.com,,noreply@badmicrosoft.com");
		isValid("billgates@badmicrosoft.com  noreply@badmicrosoft.com");
		isValid("billgates@badmicrosoft.verybad@microsoft.com");

	}

	/**
	 * @param email - The Email Address to be validated
	 * @return true if the email address is valid, else return false.
	 * 
	 * Uses the regular expression defined above to do the validation.
	 */
	public static boolean isValid(String email) {
		System.out.println(email + " >>>>>>>> is Valid? " + Pattern.matches(regex, email));
		return Pattern.matches(regex, email);
	}

}


Here is the output of this program:

billgates@badmicrosoft.com >>>>>>>> is Valid? true
billgates@nation.wide.com >>>>>>>> is Valid? true
123@badmicrosoft.com >>>>>>>> is Valid? true
'billgates@badmicrosoft.com' >>>>>>>> is Valid? false
billgates@badmicrosoft.123 >>>>>>>> is Valid? false
abc.def@badmicrosoft.com >>>>>>>> is Valid? true
abc.\def@badmicrosoft.com >>>>>>>> is Valid? false
abc_def@badmicrosoft.com >>>>>>>> is Valid? true
abc_def.@badmicrosoft.com >>>>>>>> is Valid? true
abc_def-@badmicrosoft.com >>>>>>>> is Valid? true
^billgates@badmicrosoft.com >>>>>>>> is Valid? false
billgates@badmicrosoft.com;noreply@badmicrosoft.com >>>>>>>> is Valid? true
billgates@badmicrosoft.com,noreply@badmicrosoft.com >>>>>>>> is Valid? true
billgates@badmicrosoft.com;;noreply@badmicrosoft.com >>>>>>>> is Valid? false
billgates@badmicrosoft.com;,noreply@badmicrosoft.com >>>>>>>> is Valid? false
billgates@badmicrosoft.com; noreply@badmicrosoft.com >>>>>>>> is Valid? true
billgates@badmicrosoft.com ; noreply@badmicrosoft.com >>>>>>>> is Valid? true
billgates@badmicrosoft.com , noreply@badmicrosoft.com >>>>>>>> is Valid? true
billgates@badmicrosoft.com,,noreply@badmicrosoft.com >>>>>>>> is Valid? false
billgates@badmicrosoft.com  noreply@badmicrosoft.com >>>>>>>> is Valid? false
billgates@badmicrosoft.verybad@microsoft.com >>>>>>>> is Valid? false

Programmatically Validating US and Canada Phone Numbers Using Regular Expressions In Java

The following java program checks for the validity of US and Canada phone number formats using regular expression. The regular expression used here can handle the following rules:

  • The starting character may be ‘+’ but is optional
  • If the country code is used, it can be either 0 or 1 and is optional
  • Various codes (country, area) might be separated with ‘-‘ or ‘.’ but is optional
  • Area code should not start with 0 but may be optionally enclosed in round brackets
package com.kushal.tools;
/**
 * @author Kushal Paudyal
 * Last Modified on 05/11/2011
 * Java Regular Expression to Validate US and Canada phone numbers.
 */
import java.util.regex.Pattern;

public class RegexUSAndCandaPhoneNumberValidator{
	/**
	 * REGEX IS: ^[+]?[01]?[- .]?(([2-9]d{2})|[2-9]d{2})[- .]?d{3}[- .]?d{4}$
	 * Escape Sequences are added in the following String for back slash ()
	 */
	static String phoneValidationUSCandaRegex =
		"^[+]?[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$";

	/**
	 * This method compares the parameter string against the US Phone number
	 * regex and returns true if the pattern is matched - meaning the phone
	 * number is valid.
	 *
	 * The regular expression used here can handle the following rules:
	 * The starting character may be '+' but is optional
	 * If the country code is used, it can be either 0 or 1 and is optional
	 * Various codes (country, area) might be separated with '-' or '.' but is optional
	 * Area code should not start with 0 but may be optionally enclosed in round brackets
	 *
	 */
	public static boolean isAValidUSPhoneNumber(String str) {
		return Pattern.matches(phoneValidationUSCandaRegex, str);

	}

	public static void main (String [] args ) {
		String [] phoneNumbersToValidate={"2-309-778-4234",
										  "1-309-778-4423",
										  "309-778-4235",
										  "3097784234",
										  "309.778.4234",
										  "01-309-798-4234",
										  "001-309-798-4234",
										  "0-309-798-4234",
										  "+1-309-798-4235",
										  "1-3097980577",
										  "1-309.7980578",
										  "1-(309)-788-8978"};

		for(int index=0;index<phoneNumbersToValidate.length;index++) {
			String number=phoneNumbersToValidate[index];
			boolean isValid=isAValidUSPhoneNumber(phoneNumbersToValidate[index]);
			System.out.println(number+" : "+(isValid?"Valid":"Invalid"));
		}
	}
}

US 5 and 9 Digits Zip Code Validation In Java Using Regular Expressions

ZIP codes are a system of postal codes used by the United States Postal Service (USPS) since 1963. The term ZIP, an acronym for Zone Improvement Plan, is properly written in capital letters and was chosen to suggest that the mail travels more efficiently, and therefore more quickly, when senders use the code in the postal address. The basic format consists of five decimal numerical digits. An extended ZIP+4 code, introduced in the 1980s, includes the five digits of the ZIP code, a hyphen, and four more digits that determine a more precise location than the ZIP code alone. The term ZIP code was originally registered as a servicemark (a type of trademark) by the U.S. Postal Service, but its registration has since expired. [Wikipedia / Creative Commons]

The following java class uses the regular expressions to validate the zip code. It also has tests for various sample valid and invalid zip codes.

package com.kushal.tools;
/**
 * @author Kushal Paudyal
 * Last Modified on 2010/12/12
 * www.sanjaal.com/java
 * This class demonstrates the use of regular expressions to validate US Zip code.
 * It basically validates two rules:
 * - Zip code should have five digits initially.
 * - The last four digits along with the hyphen sign are optional and can be present or absent from the zip code.
 */
import java.util.regex.Pattern;

public class ZipcodeValidatorUS {
	/**
	 * Regular Expression to match the US Zip-Code
	 */
	static final String regex = "^\d{5}(-\d{4})?$";

	/**
	 * Testing the zip code validation with some sample zip codes
	 */
	public static void main(String args[]) {

		String mixedZips[] = { 	"50266-234A", "50266-2342", "5026A-2344",
								"5026A-234A", "50266", "230" };

		int index = 0;
		boolean isMatch = false;
		while (index < mixedZips.length) {
			isMatch = isAValidZipCode(mixedZips[index]);
			System.out.println("Zip " + mixedZips[index] + " - "
					+ (isMatch ? "Valid" : "Invalid"));
			index++;
		}

	}
	
	/**
	 * This method returns true if the parameter string is a valid zip code
	 */
	public static boolean isAValidZipCode(String zip) {
		return Pattern.matches(regex, zip);
	}

}

The following is the output of this program:

Zip 50266-234A - Invalid
Zip 50266-2342 - Valid
Zip 5026A-2344 - Invalid
Zip 5026A-234A - Invalid
Zip 50266 - Valid
Zip 230 - Invalid