What is the groups() method in regular expressions in Python?

PythonServer Side ProgrammingProgramming

The re.groups() method

This method returns a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None.  In later versions (from 1.5.1 on), a singleton tuple is returned in such cases.

example

>>> m = re.match(r"(\d+)\.(\d+)", "27.1835")
>>> m.groups()
('27', '1835')

If we make the decimal place and everything after it optional, not all groups might participate in the match. These groups will default to None unless the default argument is given −

>>> m = re.match(r"(\d+)\.?(\d+)?", "27")
>>> m.groups()      # Second group defaults to None.
('27', None)
>>> m.groups('0')   # Now, the second group defaults to '0'.
('27', '0')
raja
Published on 03-Jan-2018 12:13:35
Advertisements