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, the pattern can be Pattern object.
  • string is the input string
  • flags 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 re s = '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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *