Validate the ZIP code with Java Regular expressions

Java 8Object Oriented ProgrammingProgramming

In order to match the ZIP code using regular expression, we use the matches method in Java. The java.lang.String.matches() method returns a boolean value which depends on the matching of the String with the regular expression.

Declaration − The java.lang.String.matches() method is declared as follows −

public boolean matches(String regex)

Let us see a program which validates the ZIP code with Java Regular Expressions −

Example

 Live Demo

public class Example {
   public static void main( String[] args ) {
      System.out.println(zipIndia("400709"));
      System.out.println(zipUS("10060"));
   }
   // validate zip
   public static boolean zipIndia( String z ) {
      return z.matches( "\\d{6}" );
   }
   public static boolean zipUS( String z ) {
      return z.matches( "\\d{5}" );
   }
}

Output

true
true
raja
Published on 08-Jan-2019 15:44:15
Advertisements