Python Regular Expressions in Python Introduction to Regular Expressions Name Groups

Devin Hight
Devin Hight
3,141 Points

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 62,639 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!!!

Peter Vann
MOD
Peter Vann
Treehouse Moderator 31,785 Points

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!