
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Groups Method in Regular Expressions in Python
In Python, we can use regular expressions when looking for patterns in text. So we have a useful method called groups() in Python. This method helps us to find and manage many parts of a pattern. So in this article will explain how the groups() method works.
The groups() Method
The match.group() function in Python's re module is used to get the captured groups after a successful regular expression match. When a regular expression uses parentheses, it creates capturing groups with the matched substrings. The match.group() method returns the captured substrings. The following is the syntax of the groups() method -
match.groups()
Example 1
Here is a simple example of how we can use the groups() method in Python. The pattern we will look for is a date written in the format "DD/MM/YYYY," where "DD" is the day, "MM" is the month, and "YYYY" is the year. Let's see how this works -
import re pattern = r'(\d{2})/(\d{2})/(\d{4})' text = 'The date is 25/03/2025' match = re.search(pattern, text) if match: print("Matched groups:", match.groups()) else: print("No match found")
When you run the above code, it will output the following -
Matched groups: ('25', '03', '2025')
Example 2
Here is another example of how we can use the groups() method in Python. Here we will find a person's name and age from a text string. It will check if this pattern matches the text. If a match is found, the code will print the captured groups. And it will show us the name and age separately.
import re text = "Name: Amit, Age: 30" match = re.search(r'Name: (\w+), Age: (\d+)', text) if match: print(match.groups())
When you execute the above program, it will output the following -
('Amit', '30')
Example 3
In this example, we will learn how to use Python's regular expressions to extract an email address from a string. Our goal is to determine and save the various components of an email address included in the text.
We are using the text "Contact us at [email protected]." This sentence shows that we can reach someone by email. The email address we want to extract is "[email protected]."
import re email = "Contact us at [email protected]" match = re.search(r'(\w+)@(\w+)\.(\w+)', email) if match: print(match.groups())
When you execute the above program, it will output the following -
('help', 'example', 'com')