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 Groups

vincent schouten
vincent schouten
9,687 Points

Don't quite understand the use of re.Multiline

I am not sure if I understand the concept of re.M correctly. I guess somebody uses re.Multiline to create multiple strings out of one big string. What is the need for a caret and a dollar sign? A caret specifies the beginning and the dollar the end of the string. But with re.M, every line is a string and we should not have to specify the beginning and the end of that string as it is already determined by re.M. Can somebody tell me whether I am right or wrong?

string = '''Love, Kenneth: 20 /nChalkley, Andrew: 25 /nMcFarland, Dave: 10'''

players = re.search(r''' ^(?P[\w]+) ,\s (?P[\w]+) :\s (?P[\d{2}])$ ''', string, re.X|re.M)

print(players.group()) ## gives AttributeError

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

OK, let's look at a string:

my_string = """1apple1234
2banana5678
3coconut9012"""

If I want to catch only the numbers at the end of each line, I have to use re.MULTILINE because my string has multiple lines in it and I want to treat each line as its own string for the sake of my pattern.

>>> re.match(r'\d+$', my_string, re.M)
1234

If I leave off the re.M, I'll get a totally different, and undesired, result.

>>> re.match(r'\d+$', my_string)
9012
vincent schouten
vincent schouten
9,687 Points

Hi Kenneth, your explaination is highly appreciated. Thank you.