
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Validate 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
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
Advertisements