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 trialStephen Cole
Courses Plus Student 15,809 PointsCan I cherry pick patterns within a string using Regular Expressions?
When using re, in the exercises (in Groups, for example), I have to use include a comma and a space between the two items I want. (Email and Phone.)
import re
string = '''Love, Kenneth, kenneth+challenge@teamtreehouse.com, 555-555-5555, @kennethlove
Chalkley, Andrew, andrew@teamtreehouse.co.uk, 555-555-5556, @chalkers
McFarland, Dave, dave.mcfarland@teamtreehouse.com, 555-555-5557, @davemcfarland
Kesten, Joy, joy@teamtreehouse.com, 555-555-5558, @joykesten'''
contacts = re.match(r'''
(?P<email>[-\w\d.+]+@[-\w\d.]+)
,\s
(?P<phone>\d{3}-\d{3}-\d{4})
''', string, re.M|re.X)
If I remove the comma and the space (,\s) the re won't work? Why not? The patterns, to themselves, seem to be unchanged.
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsKeep in mind that the entire regex pattern must match the target string or nothing gets returned. While the groupings help formulate the results, the comma-space is needed to properly parse the input.
Without the comma-space, The pattern would not match unless there was an email address followed by a phone number with no comma space in between.