Ted
Ted

Reputation: 497

javascript name regex

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:

The following should not be matched

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.

Upvotes: 3

Views: 187

Answers (1)

Arithmomaniac
Arithmomaniac

Reputation: 4804

^((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.

Upvotes: 3

Related Questions