Validate city and state with Java Regular Expressions

Java 8Object Oriented ProgrammingProgramming

In order to match the city and state 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 −

Example

 Live Demo

public class Example {
   public static void main( String[] args ) {
      System.out.println(city("Mumbai"));
      System.out.println(state("Goa"));
   }
   // validating the city
   public static boolean city( String c ) {
      return c.matches( "([a - zA - Z] + |[a - zA - Z] + \\s[a - zA - Z] + )" );
   }
   // validating the state
   public static boolean state( String st ) {
      return st.matches( "([a - zA - Z] + |[a - zA - Z] + \\s[a - zA - Z] + )" ) ;
   }
}

Output

false
false
raja
Published on 08-Jan-2019 11:00:48
Advertisements