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

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,673 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,673 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.