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

I just need someone to break this down for me I am getting half matches etc not all sure why I am not matching patterns

please help me break this step by step because I am at a loss why this is not working

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]+),\s
#(?P<first_name>[\w]+):\s
#(?P<score>[\d+])
""", string, re.X)

able to get match object for first name last_name match object is 'land' I am not sure why I am not matching McFarland even when I was using re.I flag

1 Answer

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

Yep - regex is difficult for me also - that's why it helps to review your code and debug it - help me gain a better understanding also.

This won't be enough to complete the challenge but should be enough to get you moving in the right direction - the challenge will also require the begin and end line identifiers along with handling multiple names (like Stewart Pinchback - two first names) - Just let me know if you need assistance with those.

Three key items:

  1. the "r" for raw string needs to be before the triple quotes
  2. the '+' plus sign for 1 or more needs to be outside the brackets for the score (or you'll only get the first digit)
  3. you also need re.M for multiline -

With just those changes you should be able to test the following in your local environment like below:

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]+),\s
(?P<first_name>[\w]+):\s
(?P<score>[\d]+)
""", string, re.M|re.X)

print(players)
# output
<_sre.SRE_Match object; span=(0, 17), match='Love, Kenneth: 20'>
print(players.groups())
# output
('Love', 'Kenneth', '20')
print(players.groupdict())
# output
{'last_name': 'Love', 'first_name': 'Kenneth', 'score': '20'}

Hope that helps