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 trialDan Oswalt
23,438 PointsRegex in python, how do I include [-\w] only up to a comma?
Regex in python, how do I include [-\w] only up to a comma? I can't think how to do this challenge, I'm not quite getting how to get a pattern of any character or hyphen the occurs right before a comma. Thanks!
import re
string = 'Perotto, Pier Giorgio'
names = re.match(r'''
(?P<lastname>[-\w]+[^,\s])
(?P<firstname>[-\w ]+)
''', string, re.X)
2 Answers
Gianmarco Mazzoran
22,076 PointsHi,
you only need to change the ^,
with \,
(since you need to escape it the comma), and remove the square brackets for the comma and the space, after the last name.
names = re.match(r'''
(?P<lastname>[-\w]+)\,\s
(?P<firstname>[-\w\ ]+\s[\w]+)
''', string, re.X)
edit: No need to escape the comma.
The comma and the space must be outside the lastname
group.
names = re.match(r'''
(?P<lastname>[-\w]+),\s
(?P<firstname>[-\w\ ]+\s[\w]+)
''', string, re.X)
Dan Oswalt
23,438 PointsJust checking, I've been staring at regex patterns for long enough today you could tell me anything was true and I'd believe you. Thank you.
Dan Oswalt
23,438 PointsDan Oswalt
23,438 PointsGreat, thank you. Now I see that I needed it outside of the group. Do I have to escape the comma though?
Gianmarco Mazzoran
22,076 PointsGianmarco Mazzoran
22,076 Pointswell, no!
Since your inside the string you don't need to escaped, my bad! I update the answer.