What is the re.match method in Python?

The re module

The re module is part of the standard library of Python. The re module allows for the use of Regular ExpressionsA sequence of characters that are used to check for pattern matches with a string or sets of strings and provides some functions, such as:

  • re.search()
  • re.match()
  • re.split()
  • re.findall()

Each function carries out a special operation on the regular expression provided as a parameter.

The re.match() function

When provided with a regular expression, the re.match() function checks the string to be matched for a pattern in the RegExRegular Expression and returns the first occurrence of such a pattern match.

This function only checks for a match at the beginning of the string. This means that re.match() will return the match found in the first line of the string, but not those found in any other line, in which case it will return null.

Syntax

re.match(pattern, string, flags)

Parameters

  • pattern: The regular expression.
  • string: The string to be checked for a match.
  • flags: Some regular expression options, such as:
    • re.I: For a case insensitive search.
    • re.L: Causes words to be interpreted according to the current locale.
    • re.S: Performs a period (dot) match at any character, including a new line.
    • re.U: Interprets letters according to the Unicode character set. How \w, \W, \b, and \B behave are usually affected.

Code example

In the code example below, we use the re.match function to find a match in the pattern pattern from the list listString.

The expressions w+ and \W will match the words starting with the letter g. If there is any string in listString that does not start with g, it won’t be recognized.

We use the for loop to check all string groups in the list for a match with the pattern.

If there is a match found, the groups() method will return each of the match set as a list, while the group() method will return the matched set of strings as a single string.

The listString list element "string dope" doesn’t match because the second string dope fails to match the pattern.

main.py
current.py
# importing the re module
import re
# string to be match save in a dictionary.
listString = ["string stay", "stringers sit","string dope"]
# loop through the dictionary and check for match
pattern = "(s\w+)\W(s\w+)"
for string in listString:
match = re.match(pattern, string)
if match:
# matched groups are printed as a separate list
print(match.groups())
# matched groups are each printed as a single string
print(match.group())
print("***************")

Free Resources