Reputation: 882
We have the need to transform a full name into an abbreviated name, where the combinations of input, vary as follows:
INPUT: [optional title] [forename or initial] [surname]
OUTPUT: [optional title] [initial] [surname]
In all instances, shown above, the output would be Mr A Smith (where a title is present) or A Smith (where it isn't present) and I figured that this would be best achieved with a RegEx, though I have no idea what the syntax would be to do this correctly.
I have tried a few myself and have only gotten mixed (incorrect) results.
As a note; the names 'could' contain special characters and no one has a middle name; so we could have someone named Mr James O'Reilly-Bond in the list, who would result in Mr J O'Reilly-Bond
This is being programmed in C#
Upvotes: 1
Views: 2169
Reputation: 1230
While not using regex is certainly an option, I understand not wanting to make the list of possible titles. If it's always 2 names or 3 with the title, you can do fine with (([A-Z])\S*)(?=\s\S*$)
, as seen https://regex101.com/r/tR7kV2/1 .
The idea is that you select the second to last word, the word is in capture group $1, its capital letter - in capture group $2, you substitute your match with $2.
Upvotes: 2
Reputation: 15784
you can achieve this with a regex Demo:
((?:mr|ms) )?(.).* (.*)
with flag i
for case insensitive and use the Three groups as substitution (you didn't say which language you're using, so I can't give an example)
The first group match an eventual title followed by a space and capture it. The second group match the first letter of the first word and the third group capture the last word (last name). There's a match for chars between second and third group to match the name format.
Upvotes: 0
Reputation: 8910
Don't use a regex. It's much easier to split the string on whitespace and then reason on each component independently (if the first one is Mr/Mrs/Ms, disregard it, otherwise take the first letter).
Upvotes: 1