BC00
BC00

Reputation: 1639

How do I split names with a regular expression?

I am new to ruby and regular expressions and trying to figure out how to attack seperating the attached string of baseball players into first/last name combinations.

This is a sample string:

"JohnnyCuetoJ.J.PutzBrianMcCann"

This is the desired output:

Johnny Cueto
J.J. Putz
Brian McCann

I have figured out how to separate by capital letters which gets me close, but the outlier names like J.J. and McCann mess that pattern up. Anyone have ideas on the best way to approach this?

Upvotes: 0

Views: 208

Answers (1)

Frost
Frost

Reputation: 11957

If you don't have to do it in one single gsub than it gets a bit easier.

string = "JohnnyCuetoJ.J.PutzBrianMcCann"
string.gsub!(/([A-Z][^A-Z]+)/, '\1 ') # separate by capital letters
string.gsub!(/(\.) ([A-Z]\.)/, '\1\2') # paste together "J. J." -> "J.J."
string.gsub!(/Mc /, 'Mc') # Remove the space in "Mc "
string.strip # Remove the extra space after "Cann "

...and of course you can put this on a single line by chaining the gsub calls, but that will basically kill the readability of the code (but on the other hand, how readable is a block of regexen anyway?)

Upvotes: 1

Related Questions