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

Extract the twitter account using regular expression with re.search()

Question: ...make a new variable, twitters that is an re.search() where the pattern catches the Twitter handle for a person. Remember to mark it as being at the end of the string. You'll also want to use the re.MULTILINE flag.

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

I tried replacing re.search with re.findall, and from the print(twitters) like below twitters = re.findall(''' ^[\w]+,\s[\w]+,\s [\w\d.+]+@[\w\d+.]+,\s [\d]{3}-[\d]{3}-[\d]{4},\s (.[\w]+)$ ''',string,re.X|re.M) print(twitters)

Output given in the console was ['@kennethlove', '@chalkers', '@davemcfarland', '@joykesten']

Thanks in advance

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

twitters = re.search('''
    ^[\w]+,\s[\w]+,\s
    [\w\d.+]+@[\w\d+.]+,\s
    [\d]{3}-[\d]{3}-[\d]{4},\s
    (.[\w]+)$
''',string,re.X|re.M)

2 Answers

Steven Parker
Steven Parker
229,744 Points

You're working to hard! You've got a very complicated regex that's anchored at both ends, but all you want in this case is just the Twitter handle from the end of the string.

Hint: the first character of a Twitter handle is always "@".

HI Steven

I wondered if I was expected to produce something like below?

twitters = re.search(''' (@[\w]+)$ ''', string, re.X|re.M)

Steven Parker
Steven Parker
229,744 Points

I expect that will pass. But you don't need the parentheses or the brackets. And since it's all on one line, you could also leave off the spaces and use normal quotes.