Grouping and Capturing
In regular expressions, you can use parentheses to group parts of the pattern and capture them for future use. This is helpful when you want to extract specific information from a larger text.
Let's say you have a string that contains multiple phone numbers, and you want to extract each phone number separately. You can use grouping and capturing to achieve this.
Here's an example of using grouping and capturing to extract phone numbers from a text:
1import re
2
3# Example: Extracting phone numbers
4
5text = 'John: 123-456-7890, Jane: 987-654-3210'
6
7# Pattern using grouping and capturing
8pattern = r'(\d{3})-(\d{3})-(\d{4})'
9
10# Find all matches
11matches = re.findall(pattern, text)
12
13# Print the matches
14for match in matches:
15 print('Phone number:', '-'.join(match))
In this example, we use the regular expression pattern '(\d{3})-(\d{3})-(\d{4})'
to match phone numbers in the format 123-456-7890
. The groups (\d{3})
, (\d{3})
, and (\d{4})
capture the three groups of digits separated by hyphens. We then use re.findall()
to find all matches in the text and print each phone number.
Grouping and capturing allows you to extract specific parts of a match and use them for further processing or analysis. It is a powerful feature of regular expressions that enhances their capabilities.
xxxxxxxxxx
import re
# Example: Extracting phone numbers
text = 'John: 123-456-7890, Jane: 987-654-3210'
# Pattern using grouping and capturing
pattern = r'(\d{3})-(\d{3})-(\d{4})'
# Find all matches
matches = re.findall(pattern, text)
# Print the matches
for match in matches:
print('Phone number:', '-'.join(match))