I am trying to create a Perl regular expression that will match a person's name. When the name ends with Sr or Jr it is formatted properly with a leading comma and space, and ending with a period.
For example:
Should match:
John Smith
John Smith, Sr.
John Smith, Jr.
Should not match:
John Smith Sr
John Smith, Sr
John Smith, SR.
John Smith Sr.
John Smith, John Smith Sr.
John Smith-
Must also be properly capitalized, i.e. Sr or Jr not sr, SR, sR, jr, JR, or jR. Name should not end with any punctuation, except for a period when Sr or Jr is used.
I tried
^(?!.(Jr|Sr)(?<!,\sJr.)(?<!,\sSr.)$).$
But the above Regex allows for several names that are not acceptable, i.e. John Smith, John Smith Sr.
I then found:
^([A-Za-z]+['-]?[A-Za-z]\s)([A-Za-z]+['-]?[A-Za-z]*)(,\s(Jr|Sr).)?$
but it allowed name to end in a hyphen, John Smith-, which should not be acceptable.
Match everything up to the last word char that isn't "Sr" or "Jr", then optionally allow ", Sr."
or ", Jr."
before end:
.*\w(?<![SJ]r)(, [SJ]r\.)?$
See live demo.
Although not "bulletproof", it works for all your test cases and should be good enough judging by your examples.