Search code examples
regexstringspecial-charactersuppercaselowercase

RegEx to enforce a typical Forename format


I would like to develop a RegEx that can enforce a typical Forename format that enforces the below:

  • First character must be uppercase letter.
  • Last character must be lowercase letter.
  • Only letters, apostrophe, fullstop, hyphen and space are allowed.
  • Consecutive punctuation is not allowed.

For example the following names would be fine: [John, Jean-Pierre, Smith.Rowe, Harry Smith]

But the following names would not be allowed [john, Jean--Pierre, Smith.-Rowe, Harry Smith (two spaces between names)]

Can anyone assist?


Solution

  • Below regex may help.
    Lower case, upper case matches can be matched with [A-Z] and [a-b].
    Consecutive punctuations, can be matched with lookaround assertions.

    ^[A-Z](?:[a-zA-Z]|(?:(?<![ .'-])[ .'-](?![ .'-])))*[a-z]$
    

    Demo