Java Program to Match Zip Codes

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 06-Dec-2018 11:39:39
Advertisements