Syntax error Validate the ZIP code with Java Regular expressions

Validate the ZIP code with Java Regular expressions



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
Updated on: 2020-06-25T15:04:40+05:30

478 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements