Java Program to Match Zip Codes



In this article, we will learn how to validate U.S. zip codes using a regular expression in Java. The program checks if a given string is a valid U.S. zip code, either in the standard five-digit format or the extended nine-digit format.

Zip Code Format

In the U.S., zip codes are five digits, with each digit representing a specific part of the United States.
Let's say we have the following zip code.

String zipStr = "12345";

Now, set the following regular expression to match zip codes in America.

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

Matching (Validating) a ZIP Code

The following are the steps to validate a ZIP code:
  • Step 1. Declare the Zip Code String: In this step, we define a string variable to hold the zip code we want to validate. This string will later be compared against the pattern to check if it's a valid U.S. zip code.
  • Step 2. Define the Regular Expression: Create a regular expression that matches the U.S. zip code format?the pattern checks for either a five-digit or nine-digit zip code with a hyphen.
String reg = "^[0-9]{5}(?:-[0-9]{4})?$";
boolean res = zipStr.matches(reg);
  • Step 3. Validate with matches() Method: Use the matches() method from the String class to check if the zip code string matches the regular expression. If it does, it confirms that the zip code is valid.

Java program to match zip codes

Below is the Java program to match zip codes.

public class Demo {
	public static void main(String[] args) {
		String zipStr = "12345";
// regular expression
		String reg = "^[0-9]{5}(?:-[0-9]{4})?$";
		boolean res = zipStr.matches(reg);
		System.out.println("Is it a valid zip code in US? "+res);
	}
}

Output

Is it a valid zip code in US? True
Updated on: 2024-11-23T03:49:21+05:30

333 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements