Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Regular Expressions in Python Introduction to Regular Expressions Name Groups

Ashley Keeling
Ashley Keeling
11,476 Points

I dont get how to do this

I'm not sure what goes in the square brackets

names.py
import re

string = 'Perotto, Pier Giorgio'

names = re.match(r'''
    (?P<lastname>
    ''',string, re.X)

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,239 Points

You've started correctly. Giving general hints here.

There are two parts to creating a group

  • the syntax overhead of naming the group (you've done this) and including the group closing paren )
  • include a regex to capture the text. Sometimes this needs to in a character set, which is a small regex wrapped by square brackets [ ]

You're looking for something of the form

(?P<lastname>regex)

In the challenge, one additional bit is needed. That is to include regex characters to capture the comma and space between the two groups.

Also remember to include a space in the character set for the first name so both parts of the "first name" are captured.

Can you figure out what the regex characters need to be to capture the first and last name?

Hint: what would capture all word characters for the first name? what would capture all word characters and spaces for the last name?

Post back if you need more help. Good luck!!!

Ashley Keeling
Ashley Keeling
11,476 Points

thanks for the help but I am stuck on the regex part, I am not sure what I am doing wrong/right

import re

string = 'Perotto, Pier Giorgio'

names = re.match(r'''
    (?P<lastname>[\w ]*[\s])
    (?P<firstname>[\w ]+)
    ''', string, re.X)

[MOD: added ```python formatting -cf]

Chris Freeman
Chris Freeman
Treehouse Moderator 68,239 Points

You are very close. The [\s] is not part of the last name group. Remember to include the comma outside of group: ,\s