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

Dmitriy Ignatiev
PLUS
Dmitriy Ignatiev
Courses Plus Student 6,236 Points

re.search groupdict()

how to find all matches and makes dict within multiply string

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+.]+@[\w.]+),\s
                    (?P<phone>\d{3}-\d{3}-\d{4})
                                       ''', string, re.X|re.M)

return only information from one line{'email': 'kenneth+challenge@teamtreehouse.com', 'phone': '555-555-5555'}

i need to get a dict with all emails and phone which string is contain {'email': 'kenneth+challenge@teamtreehouse.com', 'phone': '555-555-5555' email: 'andrew@teamtreehouse.co.uk', phone: '555-555-5556' ....till end of string}

How it could be solved?

1 Answer

Tate Price
PLUS
Tate Price
Courses Plus Student 9,987 Points

as you can see in order to find the proper characters, I had to add a few things to your code

(1) import re

(2)move the ,\s in-between email and phone

(3)add - \d to your email set in order to capture all the characters.

(4)The print statement was so that i could ensure that i got the right output in my python editor, and this is what i got:

{'email': 'kenneth+challenge@teamtreehouse.com', 'phone': '555-555-5555'}

and here is my code, I hope this helps.

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.]+)
    ,\s
    (?P<phone>\d{3}-\d{3}-\d{4})
''', string, re.X|re.M)

print(contacts.groupdict())