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

REGEX - get last name, first name, score


Could someone please help me out with what I am doing wrong here? I keep getting just Kenneth's results. I am assuming this has something to do with the different naming convention for the last record but I am not sure what to adjust to capture it (I tried adding the spaces within the names to accommodate but it is not working).


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<lastname>[\w\s\w ]+) #lastname, all word characters
    ,\s #commaspace
    (?P<firstname>[\w\s\w ]+) #firstname, all word characters
    :\s #colonspace
    (?P<score>[\d]+)$ #score
''', string, re.M|re.X)

3 Answers

I believe you want findall() instead of search().

I also have a problem with this assigment, when I'm able to match the last line I cannot match the first 4 lines and vice versa.

I think my problem is I cannot make the second element of last and first name as optional.

My current pattern: ^(?P<last_name>[\w]+\s?[\w]+?),\s(?P<first_name>[\w]+\s[\w]+):\s(?P<score>\d{2})$

Can someone help please?

Are you using re.M?

Yes, I'm testing it on regex101.com, currently it only catches the last line.