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

Why is it that the one space after the [\w ] makes all the difference?

What difference did the space on the first name expression make? Why did it work with the space, but not without one?

names.py
import re

string = 'Perotto, Pier Giorgio'
names = re.match(r'([\w]*),\s([\w ]*)',string, re.I)
#names = re.match(r'([\w]*),\s([\w]*)',string, re.I) the code I had before I figured out the space

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,636 Points

The space after the second \w is needed to match with the space in between names "Pier Giorgio".

Post back if you have more questions. Good luck!!!

Hi Devin!

You need the space you discovered because the first name 'pier' is the first name and the only word in the string with an immediate trailing space.

This also passed for me:

import re

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

So did this:

import re

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

More info:

https://www.w3schools.com/python/python_regex.asp

https://www.youtube.com/watch?v=R1PcJfzsUU0

https://regexr.com/

https://regex101.com/

I hope that helps.

Stay safe and happy coding!