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:
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.