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 Negation

Matching ', Tim'

It took me a while and a lot of playing with lookbehind assertions before I figured out that if you want to also match ', Tim' in the address book, you just need to remove the first \b (word boundary).

i.e.

print(re.findall(r'''
    [-\w]*,  # Find a word boundary, 1+ hyphens or characters, and a comma
    \s  # Find 1 whitespace
    [-\w ]+  # 1+ hyphens and characters and explicit spaces
    [^\t\n]  # Ignore tabs and newlines
''', data, re.X))

In case you were wondering, Kenneth Love

2 Answers

And now that I've progressed through the Groups step and learnt about the multiline flag (re.M), I've realised that the following will return only the names, not the jobs/companies:

print(re.findall(r'''
    ^[-\w]*,  # Find 1+ hyphens or characters, and a comma
    \s  # Find 1 whitespace
    [-\w ]+  # 1+ hyphens and characters and explicit spaces
    [^\t\n]  # Ignore tabs and newlines
''', data, re.X|re.M))

Note the caret (^) at the start of the expression to only match from the start of each line.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Someone likes regular expressions!

Yeah, they are very handy. I also love that they're in just about every good programming/scripting language out there, with relatively minor differences in syntax.

The Regular-Expressions.info site has been an excellent resource.

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Oh, yeah, I know :) We match him later.