Java RegEx – Validate US ZIP Code

Java RegEx – Validate US ZIP Code example shows how to validate US ZIP code (US postal code) using regex pattern in Java.

How to validate US ZIP code using regex pattern in Java?

A ZIP is an acronym for Zone Improvement Plan. A ZIP code is used by the United States Postal Services commonly known as USPS. The ZIP code is a 5 digit number.

However, in 1983 the ZIP code was extended by another 4 digits and is known as ZIP+4 code. The extended version enabled a more specific location to be included. The format of this code is 5 digits, followed by a hyphen, followed by another 4 digits.

Here is the regex pattern we can use to validate it.

Where,

The hyphen and another 4 digits may or may not be there. The regex group and “?” after the group addresses that because it matches 0 or 1 time. Let’s try this regex pattern out.

Output

The first code is 4 in length, so it is invalid. The second code is 6 in length, so it is invalid as well. The third code has only one digit after the hyphen. The fourth code has 5 digits after the hyphen instead of 4 so it is invalid. The fifth and sixth ZIP codes fulfill all of the requirements so they are valid codes.

If you are using JQuery or any other JavaScript library, you can also use the above-given pattern.

If you want to know more about the regex, please visit the Java RegEx tutorial.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *