Regex to validate Full name having atleast four characters

SKG picture SKG · Feb 14, 2016 · Viewed 19.7k times · Source

I want to use regex to validate names. The names must contain, first name, middle name, last name (not necessarily all). But I also want to impose a condition that the name must be of at least four characters. I have found regex to validate full name here Java Regex to Validate Full Name ... and found regex to check for checking of at least three chars (alphabets) in a string here Regex to check for at least 3 characters. But I am not sure how to combine these two to obtain the desired result. Please help me to achieve the desired Regex, so that I can complete my project.

Answer

Wiktor Stribiżew picture Wiktor Stribiżew · Feb 17, 2016

You can use

^[a-zA-Z]{4,}(?: [a-zA-Z]+){0,2}$

See the regex demo

This will work with names starting with both lower- and upper-cased letters.

  • ^ - start of string
  • [a-zA-Z]{4,} - 4 or more ASCII letters
  • (?: [a-zA-Z]+){0,2} - 0 to 2 occurrences of a space followed with one or more ASCII letters
  • $ - end of string.

If you need to restrict the words to start with Uppercase letters, you can use

^[A-Z][a-zA-Z]{3,}(?: [A-Z][a-zA-Z]*){0,2}$