I need a regex for name validation with java

Viewed 110

Hello i need a regex for name validation in java. Both first and last names are in one string. both names need to be capitalized and allow hyphenated names.

valid: John Smith, John-Doe Smith, John Smith-Doe

invalid: john smith, John-doe Smith, John Smith-doe

so far i have tried this:

[A-Z][a-z]{0,20}\s[A-Z][-a-zA-Z]{0,40}

but can't get it to catch if the name after the dash starts with lowercase

2 Answers

a slightly shorter regex would be

String regex = "[A-Z][a-z]{0,20}(?:[-\\h][A-Z][a-z]{0,40}){1,2}";

… with this change, Irish names (eg. Peter O’Toole) are also treated correctly

String regex = "[A-Z][a-z]{0,20}(?:[-\\h][A-Z](?:'[A-Z])?[a-z]{0,40}){1,2}";

You could use repeated groups that start with an uppercase A-Z, and match a whitespace or - in between.

^[A-Z][a-z]{0,20}(?:[\h-][A-Z][a-z]{0,40})*(?:,\h*[A-Z][a-z]{0,20}(?:[\h-][A-Z][a-z]{0,40})*)*$

Regex demo

In Java

String regex = "^[A-Z][a-z]{0,20}(?:[\\h-][A-Z][a-z]{0,40})*(?:,\\h*[A-Z][a-z]{0,20}(?:[\\h-][A-Z][a-z]{0,40})*)*$";
Related