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 trialJerimiah Willhite
12,014 PointsWhy would you not just use 'search' all the time? What's the use of 'match'?
Just curious as to how useful the match function is? Is it because match only returns something at the start of a line, and you can use that to differentiate between items that may have the same values but occupy different places? Does anyone have any real-world examples where it specifically would be more beneficial to use match instead of search?
1 Answer
Robert Stefanic
35,170 PointsMatch is useful, like you said, to match from the beginning of the string. That's the point of using match. Let's say I have a field where I want to check for zip codes. I don't want any 5 digits that appear in the string: I only want those 5 digits of the zip code, starting from the beginning. If there's anything else, then there won't be a match.
With that said, you could use search and add (^) to the beginning of your regular expression. This would make it so that the expression check for a match starting from the beginning of the string, not just any match found in the string.
Here's an example:
import re
# Using search to find any match in the string
re.search("4", "123456")
""" Match found """
# The following two are equivalent
re.search("^4", "123456") """ No match found """
re.match("4", "123456") """ No match found """
Jerimiah Willhite
12,014 PointsJerimiah Willhite
12,014 PointsInteresting! Thanks for the example!