Java Regex for US Zip Code Validation

Learn to use regular expressions for US zip code validation in Java. Also learn the regex rules to check a valid USA postal code.

Java regex

This java regex tutorial will teach us 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) allows 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"); //true zips.add("12345-6789"); //true //Invalid ZIP codes zips.add("123456"); //false zips.add("1234"); //false zips.add("12345-678"); //false zips.add("12345-67890"); //false 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()); }

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

Happy Learning !!

Comments

Subscribe
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.