Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 6,451 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())