CheeseConQueso
CheeseConQueso

Reputation: 6041

How can I split "lastname, firstname" into separate strings?

Whats the best way to separate the string, "Parisi, Kenneth" into "Kenneth" and "Parisi"?
I am still learning how to parse strings with these regular expressions, but not too familiar with how to set vars equal to the matched string & output of the matched (or mismatched) string.

Upvotes: 3

Views: 3779

Answers (2)

cletus
cletus

Reputation: 625097

my ($lname, $fname) = split(/,\s*/, $fullname, 2);

Note the third argument, which limits the results to two. Not strictly required but a good practice nonetheless imho.

Upvotes: 13

codelogic
codelogic

Reputation: 73622

Something like this should do the trick for names without unicode characters:

my ($lname,$fname) = ($1,$2) if $var =~ /([a-z]+),\s+([a-z]+)/i;

To break it down:

  • ([a-z]+) match a series of characters and assign it to the first group $1
  • , match a comma
  • \s+ match one or more spaces (if spaces are optional, change the + to *)
  • ([a-z]+) match a series of characters and assign it to the second group $2
  • i case insensitive match

You can change the character class [a-z] to include characters you think are valid for names.

Upvotes: 2

Related Questions