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 Counts

Sohail Mirza
seal-mask
.a{fill-rule:evenodd;}techdegree
Sohail Mirza
Python Web Development Techdegree Student 5,158 Points

Difference between + and *

With regards to Regular expression, i am confused between the difference the + and * on the notes it tells me w+ matches one or more character and * matches 0 or more

Could someone please give an example to show the difference

Thanks

1 Answer

use the * when you don't really care if a character is present because you are ok ignoring it use the + when you want to make sure the character is there for example, you could be working through a list that sometimes has Mr and sometimes does not. You might have a use case where you want to make sure you grab only the names where there is a Mr. title. Or you might have a different use case where you just care about the name and you are trying to match the name regardless of a title being present.

import re

data1 = 'abcxxxabc'
data2 = 'abcabc'

m2 = re.findall('x*abc', data1)
print(f"show a list of matches where there is an abc preceeded by zero or more x where the text is {data1}")
print(m2)

m3 = re.findall('x+abc', data1)
print(f"show a list of matches where there is an abc preceeded by one or more x where the text is {data1}")
print(m2)


m4 = re.findall('x*abc', data2)
print(f"show a list of matches where there is an abc preceeded by zero or more x where the text is {data2}")
print(m4)

m5 = re.findall('x+abc', data2)
print(f"show a list of matches where there is an abc preceeded by one or more x where the text is {data2}")
print(m5)
Sohail Mirza
seal-mask
.a{fill-rule:evenodd;}techdegree
Sohail Mirza
Python Web Development Techdegree Student 5,158 Points

Hi Frank

Really sorry for the late reply. Thank you for making the effort and explaining. Just a minor detail with regards to m3 you printed out m2 when it should be m3