Kemat Rochi Kemat Rochi - 1 year ago 106
Java Question

Using RegEx for validating First and Last names in Java

I am trying to validate a

which contains the first & last name of a person. The acceptable formats of the names are as follows.

Bruce Schneier
Schneier, Bruce
Schneier, Bruce Wayne
O’Malley, John F.
John O’Malley-Smith

I came up with the following program that will validate the String variable. The
function should return
if the name format matches any of the mentioned formats able. Else it should return

import java.util.regex.*;

public class telephone {

public static boolean validateName (String txt){
String regx = "^[\\\\p{L} .'-]+$";
Pattern pattern = Pattern.compile(regx, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(txt);
return matcher.find();


public static void main(String args[]) {

String name = "Ron O’’Henry";



But for some reason, it is returning
for any value. What am I doing wrong here?

Answer Source

Use this:




  1. The biggest problem you have is ' and is different. You can only achieve that character by copy pasting from the text.
  2. Use \- instead of - in [] since it will be mistaken as a range. For example: [a-z]
  3. You can use \s instead of for matching any whitespaces.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download