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

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,454 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,454 Points

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