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 trialManan Trivedi
2,170 PointsRegex with space:
for matching
string = 'Perotto, Pier Giorgio'
when i used ......
names = re.match(r'([\w]*), ([\w]+\s [\w]+)', string) not worked with \s
but( without \s ) worked fine names = re.match(r'([\w]*), ([\w]+ [\w]+)', string)
any idea..?
1 Answer
Joshua Yoerger
11,206 PointsManan,
You should be able to use either the \s
character or an explicit space in this situation. I notice that in your first example you have both. If you remove the explicit space after \s
the first regex should work for you. Single spaces are easy miss in code snippets and a proportional font can be even more difficult!
import re
string = 'Perotto, Pier Giorgio'
names = re.match(r'([\w]*), ([\w]+\s [\w]+)', string) # With the space after \s
names = re.match(r'([\w]*), ([\w]+\s[\w]+)', string) # Without the space after \s
Note that an explicit space and the \s
character are not strictly interchangeable as \s
is more inclusive and will find any whitespace character (e.g. a tab, a newline, etc).
Also, the brackets ([]
) are unnecessary when there is only one regex character inside.
Cheers.
Chris Freeman
Treehouse Moderator 68,457 PointsChris Freeman
Treehouse Moderator 68,457 PointsChanged to Answer.
Manan Trivedi
2,170 PointsManan Trivedi
2,170 PointsThanks!!