First name only Regular Expression

Viewed 84

I'm trying to come up with a regular expression for a first name only that should not contain the following:

  • Symbols, numbers, unusual capitalization or punctuation.
  • Characters from multiple languages – meaning one cannot have the Latin/roman alphabet mixed. with Arabic script or Katakana Japanese script.

I tried this which I found on this platform '/^(?=.{1,50}$)[a-z]+(?:['_.\s][a-z]+)*$/i'

But it accepts DaVid, DaaaaaaaaaaVid when it should fail them.

1 Answers

About the capital, adding [A-Z] and removing the i (case insensitive option) makes it:

const regex = /^(?=.{1,50}$)[A-Z][a-z]+(?:['_.\s][a-z]+)*$/

const names = [
  "DaVid",            // Rejected
  "DaaaaaaaaaaaVid",  // Rejected
  "David",            // Accepted
  "Ann",              // Accepted
  "Soooooooophie",    // Accepted
]

names.forEach((name) => console.log(regex.exec(name) ? "Accepted" : "Rejected"))

But for letters repeating more than 2 times, I don't know how that would be possible in just one regular expression.
While this one detects it:

const regex = /([a-z])\1{2,}/

const names = [
  "DaVid",           // Ok
  "DaaaaaaaaaaaVid", // Repeating char detected
  "David",           // Ok
  "Ann",             // Ok
  "Soooooooophie",   // Repeating char detected
]

names.forEach((name) => console.log(regex.exec(name) ? "Repeating char detected" : "Ok"))

Related