3

I'm trying to write a RegEx for names. Names can optionally start with a title (Dr., Mrs., etc) and otherwise contain two or three names with the middle name optionally abbreviated in the form (X.)

For instance the following names should be matched:

  • Dr. Jeff T. Walker
  • Susan B. Anthony
  • Mr. Michael Binghamton
  • Mrs. George Bush

The following should not be matched

  • Garfield
  • Dr. J
  • T. Pain
  • The United States of America
  • February 15 2020

Here is what I have:

^(Dr\.|Mr\.|Mrs\.)?[A-Z][a-z]+\s([A-Z][a-z]+|[A-Z]\.)\s[A-Z][a-z]+?

im not quite sure where I'm going wrong here.

5
  • So what exactly is not working? Commented Mar 5, 2013 at 19:29
  • so very relevant Commented Mar 5, 2013 at 19:30
  • what bout digits and symbols? 50 Cent and Ke$ha would be disappointed Commented Mar 5, 2013 at 19:30
  • @MikeHometchko, Names are typically not allowed to have numbers and symbols Commented Mar 5, 2013 at 20:26
  • I was being facetious Commented Mar 5, 2013 at 20:40

1 Answer 1

3

^((Dr|Mr|Mrs)\. )?[A-Z][a-z]+( [A-Z]([a-z]+|\.))? [A-Z][a-z]+

This is what I did to fix it:

  • Added a space after the prefix - before, you were matching things like "Dr.James", rather than "Dr. James"
  • Removed question mark at the end, after the last name - when not after a parentheses, ? results in "lazy matching" - matching as few characters as possible (in this case, 1)
  • made the middle name optional
  • Removed some redundancies (such as in the prefix and middle name)
  • replaced \s with spaces - it's easier to read, and \s matches tabs, newlines, etc.
Sign up to request clarification or add additional context in comments.

2 Comments

aha! you're a miracle worker here... been struggling with this for 30+ min. thank you for your thorough response & streamlining my existing code!
You may also want the $ at the end so you can't match something ridiculous like Dr. Jeff T. Walker !"£$%^&*()0987654321

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.