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 Name Groups

Regex 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!

names.py
import re

string = 'Perotto, Pier Giorgio'

names = re.match(r'''
  (?P<lastname>[-\w]+[^,\s])
  (?P<firstname>[-\w ]+)  
''', string, re.X)

2 Answers

Gianmarco Mazzoran
Gianmarco Mazzoran
22,076 Points

Hi,

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.py
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.py
names = re.match(r'''
  (?P<lastname>[-\w]+),\s
  (?P<firstname>[-\w\ ]+\s[\w]+)
''', string, re.X)

Great, thank you. Now I see that I needed it outside of the group. Do I have to escape the comma though?

Gianmarco Mazzoran
Gianmarco Mazzoran
22,076 Points

well, no!

Since your inside the string you don't need to escaped, my bad! I update the answer.

Just 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.