re.match

Full name
re.match
Library
re
Syntax

re.match(pattern, string, flags=0)

Description

The re.match function checks if the regular expression pattern is satisfied at the beginning of the text string, returning the corresponding match object if it is positive. In case of no match, the function returns None.

Parameters
  • pattern: Search pattern.
  • string: Text in which to search.
  • flags: Search modifiers.
Result

The re.search function returns an object of type match or None if the match is not found at the beginning of the text string.

Examples

We can check if the texts "my cat" or "my cats" are found at the beginning of several sentences with the following code:

pattern = r'my (cat)s?'
text = 'my cat and your cats are pretty'
re.match(pattern, text)
<re.Match object; span=(0, 6), match='my cat'>
text = 'my cats and your cats are pretty'
re.match(pattern, text)
<re.Match object; span=(0, 7), match='my cats'>

In this next example the regular expression is satisfied ("my cats"), but not at the beginning of the text, so the re.match function returns None (which is why nothing is displayed on the screen).

text = 'your cat and my cats are pretty'
re.match(pattern, text)
Submitted by admin on Mon, 05/17/2021 - 08:51