Validate the first name and last name with Java Regular Expressions

Java 8Object Oriented ProgrammingProgramming

In order to match the first name and last name 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 to validate the first name and last name with regular expressions −

Example

 Live Demo

public class Example {
   public static void main( String[] args ) {
      System.out.println(firstName("Tom"));
      System.out.println(lastName("hanks"));
   }
   // validate first name
   public static boolean firstName( String firstName ) {
      return firstName.matches( "[A-Z][a-z]*" );
   }
   // validate last name
   public static boolean lastName( String lastName ) {
      return lastName.matches( "[A-Z]+([ '-][a-zA-Z]+)*" );
   }
}

Output

true
false
raja
Published on 09-Jan-2019 12:10:05
Advertisements