Syntax error Validate city and state with Java Regular Expressions

Validate city and state with Java Regular Expressions



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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements