Python Regex match()
Summary: in this tutorial, you’ll learn how to use the Python regex match()
function to find a match with a pattern at the beginning of a string.
Introduction to the Python regex match function
The re
module has the match()
function that allows you to search for a pattern
at the beginning of the string
:
re.match(pattern, string, flags=0)
In this syntax:
pattern
is a regular expression that you want to match. Besides a regular expression, thepattern
can bePattern
object.string
is the input stringflags
is one or more regex flags that modify the standard behavior of the pattern.
If the search is successful, the match()
function returns the corresponding Match
object. Otherwise, it returns None
.
Note that the match()
function only matches at the beginning of the string. If you want to find a match anywhere in the string, use the search()
function instead.
Python regex match() function example
The following example uses the match()
function to check if a string starts with a digit:
import res = '3 pieces cost 5 USD'
pattern = r'\d{1}'
match = re.match(pattern, s)
if match is not None:
print(f'The string starts with a digit {match.group()}')
Code language: JavaScript (javascript)
Output:
The string starts with a digit 3
Code language: JavaScript (javascript)
Summary
- Use the
search()
function to find zero or more characters at the beginning of a string that matches a pattern.