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

regular expressions

Hi,

I cannot pass this challenge. I don't know what is wrong with my code. Thanks for your help!

names.py
import re

string = 'Perotto, Pier Giorgio'

names = re.match(r"([\w]+,) ([\w ]+)", string)

4 Answers

Travis Bailey
Travis Bailey
13,675 Points

You're REALLY close.

First you need to build in some escape characters to take the white space into account. (\s = any white-space, \S = anything that isn't white-space. Be careful with that comma in your first set also. As an example here's what my first part of the set looked like.

names = re.match(r'([\w]+),\s', string)

So the above would look for any number of unicode characters, a comma, and then white-space. The comma and white space are crucial since those provide the separation between your first and last names.

You use a very similar approach for the last part of the expressions set, but keep in mind that the first name in the string is actually two names separated by white-space.

Travis, I made your edit, but got an error saying "Bummer! Hmm, no .groups() attribute. Did you do a match?"

Travis Bailey
Travis Bailey
13,675 Points

I'm not sure why it's throwing that error, but when I typed it in the console I got.

<_sre.SRE_Match object; span=(0, 9), match='Perotto, '>

So the code is finding the last name and the comma. I didn't post the full answer on purpose.

Here's the code, line for line, that I typed into the console.

import re
string = 'Perotto, Pier Giorrgio'
names = re.match(r'([\w]+),\s', string)
names

At that point Python returned:

<_sre.SRE_Match object; span=(0, 9), match='Perotto, '>
Benny Ng
Benny Ng
6,462 Points

Sorry to tag on, but I'm having the same issue that I cannot pass this code challenge. Except, Python is returning:

<_sre.SRE_Match object; span=(0, 21), match='Perotto, Pier Giorgio'>

At this point, I'm not sure if I'm misunderstanding the challenge prompt or not.

Travis, i am working in the treehouse environment. I am still getting the same error.