-2

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?

MisterIbbs
  • 247
  • 1
  • 7
  • 20
  • seems simple enough but [why would you want to](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/)? – jhnc Sep 01 '21 at 10:37
  • For validation purposes within a Spring REST API. I can get the first two points working but the others im not too sure how to implement as a regex. – MisterIbbs Sep 01 '21 at 12:52
  • @jhnc Just on your URL, those are valid points that we shouldnt assume but i have a strict validation criteria on what data can be processed by this API hence the specific limitations. If it bites us later so be it! – MisterIbbs Sep 01 '21 at 13:26
  • There are many possible "names" that your examples do not cover but that would fit your ruleset. E.g. `A'f'h-D-fG-e.e'q` starts with an uppercase character, ends with a lowercase one and only contains the restricted characters with no consecutive punctuation. Would you really want to match it? – buddemat Sep 01 '21 at 13:38
  • There is a Verification process external to this where the names are verified against an official ID document. So the issue with non-sensical names being processed should not occur. But a good point to highlight. – MisterIbbs Sep 03 '21 at 09:24

1 Answers1

1

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

Liju
  • 2,273
  • 3
  • 6
  • 21