- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 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
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
- Related Articles
- Validate Phone with Java Regular Expressions
- Validate city and state with Java Regular Expressions
- Validate the ZIP code with Java Regular expressions
- Name validation using Java Regular Expressions
- Split First name and Last name using JavaScript?
- Constructing full name from first name, last name and optional middle name in JavaScript
- How to validate an email address using Java regular expressions.
- Search and Replace with Java regular expressions
- Display records where first and last name begins with the same letter in MySQL
- Java program to print the initials of a name with last name in full
- MySQL query to display columns name first name, last name as full name in a single column?
- MySQL GROUP BY and CONCAT() to display distinct first and last name
- Java Regular Expressions Tutorial
- Working with simple groups in Java Regular Expressions
- Working with Matcher.start() method in Java Regular Expressions

Advertisements