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.
1 |
^\\d{5}(-\\d{4})?$ |
Where,
1 2 3 4 5 |
^ - Start of the string \\d{5} - Any digit, 5 times (-\\d{4}) - regex group of hyphen followed by another 4 digits ? - Zero or 1 time $ - End of the string |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.javacodeexamples.regex; public class RegExValidateZipCode { public static void main(String[] args) { String[] strZIPCodes = { "1234", "123456", "12345-1", "12345-12345", "12345", "12345-1234" }; String strPattern = "^\\d{5}(-\\d{4})?$"; for(String strZipCode : strZIPCodes) { System.out.println(strZipCode + " => " + strZipCode.matches(strPattern)); } } } |
Output
1 2 3 4 5 6 |
1234 => false 123456 => false 12345-1 => false 12345-12345 => false 12345 => true 12345-1234 => true |
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.