Java Regex – US Zip Code Validation

In this java regex tutorial, we will learn to use regular expressions to validate USA zip codes. You can modify the regex to suit it for any other format as well.

1. Valid US ZIP code pattern

US ZIP code (U.S. postal code) allow both the five-digit and nine-digit (called ZIP + 4) formats.

E.g. a valid postal code should match 12345 and 12345-6789, but not 1234, 123456, 123456789, or 1234-56789.

Regex : ^[0-9]{5}(?:-[0-9]{4})?$

^           # Assert position at the beginning of the string.
[0-9]{5}    # Match a digit, exactly five times.
(?:         # Group but don't capture:
  -         #   Match a literal "-".
  [0-9]{4}  #   Match a digit, exactly four times.
)           # End the non-capturing group.
  ?         #   Make the group optional.
$           # Assert position at the end of the string.

2. US Zip Code Validation Example

List<String> zips = new ArrayList<String>();
      
//Valid ZIP codes
zips.add("12345");  
zips.add("12345-6789");  

//Invalid ZIP codes
zips.add("123456");  
zips.add("1234");  
zips.add("12345-678");

zips.add("12345-67890");

String regex = "^[0-9]{5}(?:-[0-9]{4})?$";

Pattern pattern = Pattern.compile(regex);

for (String zip : zips)
{
	Matcher matcher = pattern.matcher(zip);
	System.out.println(matcher.matches());
}

Output:

true
true

false
false
false
false

That was pretty easy, right? Drop me your questions related to how to validate US zip code using regular expressions.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Java Regex – US Zip Code Validation”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.