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 Players Dictionary and Class

January Johnson
January Johnson
23,855 Points

Didn't get the expected match

When I run my code in VSCode I get <re.Match object; span=(0, 17), match='Love, Kenneth: 20'>

But Treehouse keeps giving me

Bummer: Didn't get the expected match. Got "{'last_name': 'Love', 'first_name': ' Kenneth', 'score': ' 20'}".

players.py
import re

string = '''Love, Kenneth: 20
Chalkley, Andrew: 25
McFarland, Dave: 10
Kesten, Joy: 22
Stewart Pinchback, Pinckney Benton: 18'''

players = re.search(r'''
(?P<last_name>[\w]+\s?[\w]+?), #last name
(?P<first_name>\s[-\w]*?\s?[\w]*): #first_name
(?P<score>\s[\d]+) #score
''', string, re.X|re.M)

2 Answers

Steven Parker
Steven Parker
228,991 Points

The regex should account for spaces between the elements, but not include leading spaces as part of the elements.

Got "{'last_name': 'Love', 'first_name': ' Kenneth', 'score': ' 20'}
                                          ^                    ^
                                          |-- leading spaces --|
January Johnson
January Johnson
23,855 Points

Figured it out. I just needed to change where I was putting \s. Still, I wonder why I couldn't get the lookaround sequence to work. ??

Steven Parker
Steven Parker
228,991 Points

The lookbehind would match a name that folllows a space, but it doesn't account for having a space between the comma and the name. You still need a space (or space character class) in between the named ranges.

January Johnson
January Johnson
23,855 Points

I see. Unfortunately, the only way I understand to match but not capture the \s is to use a lookaround expression (?<=\s). But it doesn't work.