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

Andrei Oprescu
Andrei Oprescu
9,547 Points

no .groups() attribute. What does that mean?

Hi!

I have come across this question in a code challenge:

Create a variable names that is an re.match() against string. The pattern should provide two groups, one for a last name match and one for a first name match. The name parts are separated by a comma and a space.

My attempt at this code challenge looked like the one at the bottom of this question.

What have I done wrong and how can I solve this challenge?

Thanks!

Andrei

names.py
import re

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

2 Answers

Eric M
Eric M
11,546 Points

Hi Andrei,

.groups() is a method that returns the groups in a match object, I think in this case it's trying to say the match object doesn't have any data.

So let's take a look at the regex

r'([-\w\s]+]), ([-\w]+])'

Two things jump out at me. In both of your groups you have a two closing square brackets but only one opener. This is probably what's causing your regex to fizzle.

r'([-\w\s]+), ([-\w]+)'

Okay, now that we've got rid of those we need to be sure we're matching the right data. In this case the string is in the format of lastname comma space firstname, where firstname can contain a space. Your regex at this point is pretty much correct, you've just got to switch your two groups around so that the set containing the space is second not first.

r'([-\w]+), ([-\w\s]+)'

That should do it!

Regular expression patterns can be pretty confusing, I always have to fiddle with them a bit.

Good luck!

Andrei Oprescu
Andrei Oprescu
9,547 Points

Thanks! I did not realize I have added two more square brackets to my code and that I switched my name around!

Andrei