Validate the first name and last name with Java Regular Expressions


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

Updated on: 25-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements