groups() method in Regular Expression in Python

In this tutorial, we will learn about groups() method in Regular Expression in Python. We will learn what regular expressions are and how we can use them with the help of an example.

About Regular Expressions

A regular expression (RegEx) can be referred to as the special text string to describe a search pattern. It allows to check a series of characters for matches. Since we want to use the groups() method in Regular Expression here, therefore, we need to import the module required. Python already has a module for working with regular expressions which is the re module. Following is an example to understand this concept:

import re

search = '^n....h$'     # it shows that word should be 6 letters
test1 = "nimish"
test2 = "nimisH"        # will not match as last letter is capital
result1 = re.match(search, test1)
result2 = re.match(search, test2)

if result1:
    print("Search successful")
else:
    print("Search unsuccessful")
if result2:
    print("Search successful")
else:
    print("Search unsuccessful")

Output:

Search successful
Search unsuccessful

groups() method in Regular Expression in Python

groups() method returns a tuple containing all the subgroups of the match, therefore, it can return any number of groups that are in a pattern. Since there can be a condition in which no group is in patter then it returns default value,i.e, None. Unlike groups(), the group() method returns the entire match.

Code

Following is a code to understand the concept of groups() method:

import re

m = re.match(r"(\d+)\.(\d+)", "13.2370")
print(m.groups())
print(m.group())

Output:

('13', '2370')
13.2370

Explanation

  • The match() method attempts to match regular expression pattern with the entered string.
  • The groups() method thus returns the tuple of matched groups.
  • The group method returns the entire group at a time.

I hope you were able to understand this topic. Feel free to comment on any of your queries or any other topic you would like to know about.

Also read: Python string.hexdigits and its example

Leave a Reply