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

William Higgins
William Higgins
5,904 Points

For the contacts code challenge, my code is getting nowhere.

Here is my code.

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'''

#print(string)
contacts = re.search(r'''
    ^(?P<name>[-\w ]+,\s[-\w ]+),\s                    # last and first names
    (?P<email>[-\w\d.+]+@[-\w\d.]+),\s         # email
    (?P<phone>\d{3}-\d{3}-\d{4}),\s  # phone
    (?P<twit>@[\w\d]+)$                                 #twitter
''', string, re.X | re.M)

print(contacts)
print(contacts.groupdicts())

The challenge is to get just the email and phone. I could not do that so I added the name and twit groups, but that does not run either.

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

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

you are very close. For Task 1 of 2, you don't need to match the entire line. The solution asks only for the and the email. commenting out a bit of your regex passes Task 1 of the challenge:

contacts = re.search(r'''
    # no name ^(?P<name>[-\w ]+,\s[-\w ]+),\s                    # last and first names
    (?P<email>[-\w\d.+]+@[-\w\d.]+),\s         # email
    (?P<phone>\d{3}-\d{3}-\d{4}),\s  # phone
    # no tweet (?P<twit>@[\w\d]+)$                                 #twitter
''', string, re.X | re.M)

For Task 2 of 2, I changed the commented lines of your regex:

contacts = re.search(r'''
    # no name ^(?P<name>[-\w ]+,\s[-\w ]+),\s                    # last and first names
    # no email (?P<email>[-\w\d.+]+@[-\w\d.]+),\s         # email
    #  no phone (?P<phone>\d{3}-\d{3}-\d{4}),\s  # phone
    (?P<twit>@[\w\d]+)$                                 #twitter
''', string, re.X | re.M)

You clearly get regex syntax. the mistake is in over searching for the whole string.

Remember, when using match(), the whole pattern must match, with search() only a portion must match. However, when you use search() and use the beginning anchor "^" and the ending anchor "$", you are effectively doing a whole string "match".