Published Jul 30, 2021Updated Jun 10, 2022
Contribute to Docs
.search() method returns the first match of a character pattern anywhere in a given string.
re.search(<pattern>, string, <optional args>)
<pattern> is a regular expression that can include any of the following:
- A string:
- A character class code:
- A regex symbol:
There are optional arguments that include the following:
- A starting index value (pos):
- An index value to end the search (endpos):
.search() will only return the the first match (as a match object) within the string; alternatively, the
.findall() method matches every occurrence (and returns a list of matches).
All content that appears within parentheses are matched with the
.search() method in the example below:
import reresult = re.search(r"\(.*\)", "the coordinates (lat:48,lon:-120)")# Backslashes designate a symbol as part of the patternprint(result)
The output will look like this:
<re.Match object; span=(16, 33), match="(lat:48,lon:-120)">
The following example features a regex that uses the
.search() method to match a web address:
import reresult = re.search(r"www\S+", "the tutorials at www.codeacademy.com")# \S matches any character except a space, tab or newlineprint(result)
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
Language ParsingApply regular expressions (regex) and other natural language parsing tactics to find meaning and insights in the texts you read every day.
Learn the Basics of Regular ExpressionsGet a taste of regular expressions (regex), a powerful search pattern language to quickly find the text you're looking for.
Text PreprocessingLearn to clean text with Python 3 using regular expressions (regex) and NLTK.