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 trialMark Chesney
11,747 Pointsregex sets trailing comma
This is challenging; I've passed this challenge earlier this summer. I can't pass it now.
SHOULD RETURN:
"kenneth@teamtreehouse.com"
but it erroneously returns a trailing comma at the end:
"kenneth@teamtreehouse.com,"
Thank you!
import re
# Example:
# >>> find_email("kenneth.love@teamtreehouse.com, @support, ryan@teamtreehouse.com, test+case@example.co.uk")
# ['kenneth@teamtreehouse.com', 'ryan@teamtreehouse.com', 'test@example.co.uk']
def find_emails(string):
return re.findall(r'\w+\W?\w*@\w+.\w+.?\w*', string)
# Got ['kenneth@teamtreehouse.com,', 'andrew+gotcha@teamtreehouse.com,', 'exa.mple@example.co.uk'],
# expected ['kenneth@teamtreehouse.com', 'andrew+gotcha@teamtreehouse.com', 'exa.mple@example.co.uk'].
2 Answers
Chris Freeman
Treehouse Moderator 68,427 PointsChallenging question! The issue is trying to capture the second optional period and domain extension. By using ".?\w*
" with no qualifiers, the period means any optional character followed by zero or more word characters. This is fine in the third match, but causes the comma to be accepted in the first two matches.
The fix is to specify the period is literal and not a wildcard. Precede it with a backslash to look for a literal period: "\.?\w*'
"
If youβre looking for a more dense and readable solution, try using of character sets to list groups of valid characters, such as:
[.+\w]+
[.\w]+
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsI got it to work by adding the 'word boundary' \b
at the end of the regex.
def find_emails(string):
return re.findall(r'\w+\W?\w*@\w+.\w+.?\w*\b', string)
Mark Chesney
11,747 PointsMark Chesney
11,747 PointsThanks Chris!! So when you say:
does that mean anything at all, including letters, numbers, etc.?
Chris Freeman
Treehouse Moderator 68,427 PointsChris Freeman
Treehouse Moderator 68,427 PointsYes, in regex, a β.β (period) means any character. So β.?β means any optional character. And β.*β means any number of any character. A literal period needs the backslash.