You are viewing limited content. For full access, please sign in.

Question

Question

Separate First Middle Last Name

asked on May 18, 2020

I have a field with the full name of a person. How do I use regular expressions to separate them into First, Middle, and Last name. The middle name could be anywhere from zero names to whatever many names they input. Thanks!

0 0

Answer

SELECTED ANSWER
replied on May 18, 2020 Show version history

If at all possible, you want to avoid doing any kind of programmatic manipulation of people's names. If it's important for you to have separate First, Middle and Last name fields, the user should fill those out themselves, rather than you trying to extract them. If you've never read https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/ it's worth a look. The approach you've outlined will end up with last names like "Jr." and "IV" given reasonable inputs - and that's if you remember to allow periods in your regex. I regularly receive mail addressed to "Keever, Brian Mc" - and I *never* write my name with a space!

All that said, sometimes you don't get to dictate the requirements. Making the fewest assumptions you can here is important. Spaces separate names, and anything else is part of a name. So you want something like:

([^\s]+)\s([^\s].*?)?\s?([^\s]+)

\s is a space character, so ^\s is part of a name. This assumes there is only 1 space between names, if that's not true you'll need to adjust to account for it.

2 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.