Reputation: 497
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
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:
?
results in "lazy matching" - matching as few characters as possible (in this case, 1)\s
with spaces - it's easier to read, and \s matches tabs, newlines, etc.Upvotes: 3