re.match()
Anonymous contributor
Published Jun 10, 2022Updated Sep 5, 2023
Contribute to Docs
The .match()
method returns a matching character pattern at the beginning of a given string.
Syntax
re.match(<pattern>, string, <flags>)
A <pattern>
can include any of the following:
- A string:
Jane
- A character class code:
/w
,/s
,/d
- A regex symbol:
$
,|
,^
The <flags>
are optional and can be set to IGNORECASE
, VERBOSE
, or 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
In the example below, the .match()
method is used to find a pattern at the beginning of the string:
import reresult = re.match(r"www", "www.codeacademy.com")print(result)
The output will look like this:
<_sre.SRE_Match object; span=(0, 3), match="www">
Codebyte Example
The following example returns a match object (<re.Match object; span=(0, 12), match='123-456-7890'>
) and not None
since the phone number (123-456-7890
) matches the test pattern:
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