How to use regular expressions

Certainly! Let’s say you have a string in the format “name132address456phone789” where you want to extract both the name and the numbers separately. Here’s an example using multiple groups in a regular expression:

import re

string = "name132address456phone789"

# Extract name and numbers using regular expressions
match = re.search(r'(name)(\d+)(address)(\d+)(phone)(\d+)', string)

name = match.group(1)
number1 = match.group(2)
address = match.group(3)
number2 = match.group(4)
phone = match.group(5)
number3 = match.group(6)

print("Name:", name)
print("Number 1:", number1)
print("Address:", address)
print("Number 2:", number2)
print("Phone:", phone)
print("Number 3:", number3)

In this example, we have six groups defined within the regular expression pattern:

By calling group(n) on the Match object, we can retrieve the matched substrings for each group. The numbers in the group calls correspond to the group number.

The output of the above code will be:

Name: name
Number 1: 132
Address: address
Number 2: 456
Phone: phone
Number 3: 789

As you can see, we extracted the name and three sets of numbers separately using multiple groups in the regular expression.