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 Negated Numbers

Y B
Y B
14,136 Points

Regex negation - I'm sure this must be right but it doesn't work

Hmm I really can't see why this doesn't work, but it fails the challenge.

negate.py
import re

string = '1234567890'

good_numbers = re.findall(r'\d*[^567]', string)

4 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

You can click the "Preview" button during the CC and it'll show you what your variables are catching. Anything weird show up?

Chris Christensen
Chris Christensen
9,281 Points

Anybody reading this one is going to be greatly confused by Michael's assertion that you need to define a set before you can do a negation set. That sent me in circles and quite honestly I got this one by accident. If you are not wanting the answer, look away now because I think that it is possible to conclude the answer from Kenneth's last response. But, if you'd like to do a facepalm like I did here is the answer...

!!!!SPOILER ALERT!!!!

import re

string = '1234567890'

good_numbers = re.findall(r'[^567]', string)

You have to define a set in order to define a negation set.

import re

string = '1234567890'

good_numbers = re.findall(r'\d[,9][^567]', string)
Y B
Y B
14,136 Points

Oh is that true, I didn't realise that there had to be a set to define a negation set.

Your version didn't work for me though and the output was still ['1234567890']

..... Actually it does if I remove the star from \d* which I had left in.
Interestingly if I leave out the \d altogether it still works. Presumably it then just looks at the sets only?

However this doesn't work which I don't understand? Isn't this picking up a group of 1 or more numbers i.e. [\d+], then removing from that set 567? which should work?

import re

string = '1234567890'

good_numbers = re.findall(r'[\d+][^567]', string)
Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher
>>> import re
>>> string = '1234567890'
>>> re.findall(r'[\d+][^567]', string)
['12', '34', '78', '90']

Basically it's looking for a set of 1+ numbers and then not a 5, a 6, or a 7. The string only has numbers in it, so you don't really need the \d.

Remember, you can check the Preview tab during the CC to see what you're getting.