Python RegEx Match Object Functions

In Python, as we know, the match() and search() method returns a re.Match object if a match found. A Match Object is an object containing information about the search and the result.

If there is no match, the value "None" will be returned, instead of the Match Object.

The Match object has properties and methods used to give information about the search and the result:

  • .span(): It returns a tuple containing the start and end positions of the match
  • .string: It returns the string passed into the function
  • .group(): It returns the part of the string where there was a match

Example:

import re

str_1 = "Welcome to Python Programming "
res_1 = re.search(r"\bP\w+", str_1)
print(res_1.span())
res_2= re.search(r"\bP\w+", str_1)
print(res_2.string)
res_3 = re.search(r"\bP\w+", str_1)
print(res_3.group())

Output:
(11, 17)
Welcome to Python Programming
Python

Tags