Python | How to improve my regex which validates names?

Viewed 63

I have a Python regex which validates names given by a user in a chatbot.

(?=.{2,100}$)[^\W\d_]{2,}(?:[-\s][^\W\d_]{2,})*

As you can see in the demo, it works great, but I have still problems for the following inputs:

  • Mathias d'Arras
  • Mike O'Neal
  • Peter.
  • Peter?
  • Peter!
  • Boby-Dick.
  • Boby-Dick?
  • Boby-Dick!

As you can see, I want my regex match even if the user types his name with a punctuation mark. How would you improve the regex?

1 Answers

To enhance the current pattern you can replace {2,} limiting quantifiers with + to allow single char prefixes like O' or d' and add an optional [.?!]? pattern at the end:

^(?=.{2,100}$)[^\W\d_]+(?:[-' ][^\W\d_]+)*[.?!]?$

See the regex demo. You may add more punctuation chars you want to allow at the end of the name into the character class (remember to escape ^, ], - and \ inside square brackets).

Details:

  • ^ - start of string
  • (?=.{2,100}$) - there must be two to 100 chars in the string
  • [^\W\d_]+ - one or more letters
  • (?:[-' ][^\W\d_]+)* - zero or more occurrences of a space, ' or - followed with one or more letters
  • [.?!]? - an optional ?, !, .
  • $ - end of string.
Related