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

Michael Steinman
Michael Steinman
11,012 Points

Regular Expressions: players challenge task 1 of 2

This is the task with the string:

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

I need to match three groups with re.search: last_name, first_name, and score. I was able to complete the challenge, but I have a lingering question.

The first time I wrote my RE pattern, I used the set [a-zA-Z]+ to capture the last name. Of course, the lack of white space in the set will fail to catch the last last name in the string. That's obvious, but what I was surprised about was the fact that the code checker caught this mistake. I was expecting the re.search to only catch the first match: "Love, Kenneth: 20". When I run this code in Python, I get

>>> players
<_sre.SRE_Match object; span=(0, 17), match='Love, Kenneth: 20'>

Can you help me understand this? Is the code checker running a loop on all lines?

players.py
import re

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

[MOD: added ```python formatting -cf]

1 Answer

Yes, if you don't have the multiline flag (re.M), it treats the new lines as a special character in the middle of a long string. When you do have that flag, it treats the end of each line as the end of the string to match.