Fix the regular expression used in the rearrange_name function so that it can match middle names, middle initials, as well as double surnames

Question:

Can anyone try to figure out how to fix this code:

import re
def rearrange_name(name):
  result = re.search(r"^(w*), (w*)$", name)
  if result == None:
    return name
  return "{} {}".format(result[2], result[1])

name=rearrange_name("Kennedy, John F.")
print(name)

it‘s supposed to output "John F., Kennedy"

Asked By: Yilin Zuo

||

Answers:

As MYousefi pointed out, your regular expression isn’t compatible with middle names. I found out the following using regex101:

  • w matches any word character (equivalent to [a-zA-Z0-9_])

The string "John F." contains two characters what aren’t word characters:

  • Space ( )
  • Dot (.)

Fixing your original regex would look like this (I would recommend + instead of *):

^(w+), ([w. ]+)$

To handle "double surnames", you have to allow spaces and hyphens in the first group:

^([w -]+), ([w. ]+)$

Alternate solution

It might be easier to solve your problem using str.split() and str.join() instead of using regex:

def rearrange_name(name):
    tokens = name.split(", ")
    return " ".join(reversed(tokens))

name=rearrange_name("Kennedy, John F.")
print(name)

This codes splits the name, re-arranges the two halves and joins them back together.

Answered By: Anton Yang-Wälder

I already know how!

import re
def rearrange_name(name):
  result = re.search(r"^([w .-]*), ([w .-]*)$", name)
  if result == None:
    return name
  return "{} {}".format(result[2], result[1])

name=rearrange_name("Kennedy, John F.")
print(name)
Answered By: Yilin Zuo

This is what I used and it worked.

import re
def rearrange_name(name):
  result = re.search(r"^(w*), (.*)$", name)
  if result == None:
    return name
  return "{} {}".format(result[2], result[1])

name=rearrange_name("Kennedy, John F.")
print(name)
Answered By: Ndiana
import re
def rearrange_name(name):
  result = re.search(r"^(w*), (w*.*)$", name)
  if result == None:
    return name
  return "{} {}".format(result[2], result[1])

name=rearrange_name("Kennedy, John F.")
print(name)
Answered By: user2181613
import re
def rearrange_name(name):
  result = re.search(r"^(w*), ([a-zA-Z]*.*)$", name)
  if result == None:
    return name
  return "{} {}".format(result[2], result[1])

name=rearrange_name("Kennedy, John F.")
print(name)
Answered By: user2181613
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.