Java Program to Match Zip Codes


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})?$";

Example

 Live Demo

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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 25-Jun-2020

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements