RegEx to match names?

P

Patrick D.

There are a few different name formats out there, and I'm having trouble
incorporating them into one regex.

e.g.

George Walker Bush
George W. Bush
George Bush
G. Walker Bush
G. W. Bush
G.W. Bush

What I want is a way to always be able to identify the first+middle and
last names. I'd like the $1 to be "George Walker" or "George W." or G.
Walker", or just "George" if there is no middle. With $2, hopefully it
could contain *only* "Bush".

Can anyone help me make a regex for all the above?
 
S

Sam Holden

There are a few different name formats out there, and I'm having trouble
incorporating them into one regex.

e.g.

George Walker Bush
George W. Bush
George Bush
G. Walker Bush
G. W. Bush
G.W. Bush

What I want is a way to always be able to identify the first+middle and
last names. I'd like the $1 to be "George Walker" or "George W." or G.
Walker", or just "George" if there is no middle. With $2, hopefully it
could contain *only* "Bush".

Can anyone help me make a regex for all the above?

/(.*)\s+(\S+)/;

For something more robust you could try a module like Lingua::En:NameParse.
 
S

Sam Holden

/(.*)\s+(\S+)/;

The + in \s+ might as well be dropped, since if there are multiple
spaces, the .* is going to grab them leaving just one for the \s+ anyway.

Or the .* could be replaced with .*?, if trailing spaces in $1 aren't
wanted.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top