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 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.