JasonBorne JasonBorne - 7 months ago 25
Ruby Question

Regex to grab full firstname and first letter of last name

I have a list of users grabbed by the

Etc
Ruby library:


Thomas_J_Perkins

Jennifer_Scanner

Amanda_K_Loso

Aaron_Cole

Mark_L_Lamb


What I need to do is grab the full first name, skip the middle name (if given), and grab the first character of the last name. The output should look like this:


Thomas P

Jennifer S

Amanda L

Aaron C

Mark L


I'm not sure how to do this, I've tried grabbing all of the characters:
/\w+/
but that will grab everything.

Answer

You don't always need regular expressions.

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. Jamie Zawinski

You can do it with some simple Ruby code

string = "Mark_L_Lamb"
string.split('_').first + ' ' + string.split('_').last[0]
=> "Mark L"