Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex to validate a name

Tags:

java

regex

To validate names that can be

John, John Paul, etc.

I use this regex:

String regex = "[A-Z]([a-z]+|\\s[a-z]+)";

but when I do:

boolean ok = Pattern.matches(regex, "John Paul");

the matches fail?

Why? I want to use matches to validate the string as whole...

Is that regex wrong?

like image 244
xdevel2000 Avatar asked Aug 12 '26 08:08

xdevel2000


2 Answers

You are going to have lots of problems with validating names - there are lots of different types of names. Consider:

  • Jéan-luc Picard
  • Carmilla Parker-Bowles
    • Joan d'Arc
  • Matt LeBlanc
  • Chan Kong-sang (Jackie Chan's real name)
  • P!nk
  • Love Symbol #2

The easiest thing to do is to get the user to enter their name and accept it as is. If you want to break it up into personal name and family names for things such as personalisation, then I suggest you break up the input fields into two (or more) parts, or simply ask for a "preferred name" or "nickname" field.

I doubt you'll find a regex that can validate all the variety of names out there - get a big set of sample data (preferably real-world) before you start trying.

like image 173
Robert Watkins Avatar answered Aug 13 '26 21:08

Robert Watkins


Paul has a capital P and your regex doesn't allow for capitalization at the start of the second word.

like image 41
Noel M Avatar answered Aug 13 '26 22:08

Noel M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!