re.search()
Anonymous contributor
Published Jul 30, 2021Updated Sep 5, 2023
Contribute to Docs
The .search()
method returns the first match of a character pattern anywhere in a given string.
Syntax
re.search(<pattern>, string, <optional args>)
A <pattern>
is a regular expression that can include any of the following:
- A string:
Jane
- A character class code:
/w
,/s
,/d
- A regex symbol:
$
,|
,^
There are optional arguments that include the following:
- A starting index value (pos):
3
- An index value to end the search (endpos):
40
- Flags:
IGNORECASE
,VERBOSE
,DOTALL
Note:
.search()
will only return the first match (as a match object) within the string; alternatively, the.findall()
method matches every occurrence (and returns a list of matches).
Example
All content that appears within parentheses is 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)">
Codebyte Example
The following code example demonstrates the usage of re.search()
with a regular expression to find and match the first email address within a given text.
All contributors
- Anonymous contributor
- Anonymous contributor
- Anonymous contributor
- Anonymous contributor
- CaupolicanDiaz
- BrandonDusch
- StevenSwiniarski
- christian.dinh
Contribute to Docs
- 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
- Course
How to Clean Data with Python
Learn the basics of regular expressions and how to pull and clean data from the web with Python.With CertificateIntermediate3 hours - Course
Language Parsing
Apply regular expressions (regex) and other natural language parsing tactics to find meaning and insights in the texts you read every day.With CertificateIntermediate2 hours - Free course
Learn the Basics of Regular Expressions
Get a taste of regular expressions (regex), a powerful search pattern language to quickly find the text you're looking for.Beginner Friendly1 hour - Course
Text Preprocessing
Learn to clean text with Python 3 using regular expressions (regex) and NLTK.With CertificateIntermediate2 hours