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 Email Groups

Help me with Email grouping Regex

can someone help me figure out why this code doesn't working , but if I just search an email or just phone that code working but just get 1 line of the string

I think after adding flag re.MULTIPLELINE the other line got grab also but not yet clear

emails.py
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.search(r'''
  (?P<email>[-\w\d.+]+@[-\w\d.]+)  # Email
  (?P<phone>\d{3}-\d{3}-\d{4})  # Phone number
  [^\s,]  # Ignore space and comma
''', string, re.X|re.M)

2 Answers

contacts = re.search(r'''
  (?P<email>[-\w\d.+]+@[-\w\d.]+),\s  # Email
  (?P<phone>\d{3}-\d{3}-\d{4})  # Phone number
''', string, re.X|re.M)

aw found that way :3 ... but any suggestion appreciated

Steven Parker
Steven Parker
230,995 Points

:point_right: It looks like you forgot to account for the comma and space between the email and phone number, plus that extra "Ignore" group at the end is keeping the phone number from matching.

I find comments inside a string awkward (and it defeats the syntax coloring), but you can have them outside if you break the string up in pieces:

contacts = re.search(
  r'(?P<email>[-\w\d.+]+@[-\w\d.]+),\s'  # Email
  r'(?P<phone>\d{3}-\d{3}-\d{4})'  # Phone number
  , string, re.M)

(admittedly, breaking the string up has nothing to do with passing the challenge)

(I forgot to remove the re.X the first time - thanks, Chris)

Chris Freeman
Chris Freeman
Treehouse Moderator 68,426 Points

The purpose of the re.X (verbose) argument is to ignore whitespace, linebreaks, and comments in the regex string. So comments are allowed.

By breaking the string up into multiple strings, the re.X flag is not needed. This will also pass:

contacts = re.search(
  r'(?P<email>[-\w\d.+]+@[-\w\d.]+),\s'  # Email
  r'(?P<phone>\d{3}-\d{3}-\d{4})'  # Phone number
  , string, re.M)