Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Regular Expressions in Python Introduction to Regular Expressions Sets

Welby Obeng
Welby Obeng
20,340 Points

Can someone explain the + well for me

In search = r"[-\w\d+.]+@[-\w\d+]+" why do we need to add + in the set and outside of the set. What are we saying when we add it and not add it

3 Answers

KAZUYA NAKAJIMA
KAZUYA NAKAJIMA
8,851 Points

I thought + sign inside first [] is just intended to catch doctor's email address which has '+' inside it.

doctor+companion@tardis.co.uk

However, + sign outside [] means 'match any character inside [], once or more'

I'm not confident but it seems right...

David Axelrod
David Axelrod
36,073 Points

This is my understanding as well!

example:

>>> text = "2+4 you+me"

# []+ searches for 1 or more of whatever is inside []
>>> re.findall(r'\b[\w]+\b', text)
['2', '4', 'you', 'me']

# [+] searches for '+' in text
>>> re.findall(r'\b[\w+]\b', text)
['2', '+', '4', '+']

# both inside and out
>>> re.findall(r'\b[\w+]+\b', text)
['2+4', 'you+me']

Inside your square brackets, you're defining the group of allowed characters in the string that you're looking for, i.e. dashes (-), word characters (\w), numbers (\d), plus signs (+) and points (.). Outside the square brackets, when you use the plus sign, you're saying that there can be any number of any of the group of allowed characters in that string.

It's a small difference, but an important one.

Welby Obeng
Welby Obeng
20,340 Points

Can you please explain with examples. What do you mean allow in any group of characters?

William Li
William Li
Courses Plus Student 26,867 Points

Welby, I suggest that you re-watch the video, Kenneth Love covers that during the lectures with examples.

Welby Obeng
Welby Obeng
20,340 Points

William I tried that already...thank you

I want to know the difference in the + in the set vs the + outside the set