Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Regular Expressions in Python Introduction to Regular Expressions Name Groups

Can't select the first and last name in different groups for the code challenge.

I have been stuck on this for hours, regex is very frustrating.

names.py
import re

string = 'Perotto, Pier Giorgio'
names = re.match('''
    (?P<last_name>[-\w]+,\s)  # last name
    (?P<first_name>[-\w]+\s[-\w]+)  # first name
    ''', string, re.M|re.X)

This is the best that I've got so far:

name = re.match('''
    (?P<last_name>[-\w]+,\s)  # last name
    (?P<first_name>[-\w]+\s[-\w]+)  # first name
    ''', string, re.M|re.X)

Which gave me:

{'last_name': 'Perotto, ', 'first_name': 'Pier Giorgio'}

1 Answer

Steven Parker
Steven Parker
231,271 Points

You are sooooo close. You just need to exclude the separator from the last name group (by moving the closing parenthesis):

names = re.match('''
    (?P<last_name>[-\w]+),\s  # last name
    (?P<first_name>[-\w]+\s[-\w]+)  # first name
    ''', string, re.M|re.X)

It's always the simplest things that get me! Thanks!