Capturing
Lesson 17 of 28 in Coddy's RegEx in Python course.
Capturing groups not only group parts of a pattern but also capture the matched text. These captured groups can be referenced later in the pattern or used in the replacement string in substitution.
import re
text = "abab abab abab"
pattern = r"(ab)\1"
matches = re.findall(pattern, text)
print(matches) # Output: ['ab', 'ab']In the above example, the pattern (ab)\1 captures the group "ab" and then looks for the same group immediately after it. The \1 is a backreference to the first captured group.
Another example:
import re
text = "My email is example@example.com and my backup is backup@example.com."
pattern = r"(\w+)@example\.com"
matches = re.findall(pattern, text)
print(matches) # Output: ['example', 'backup']In the above example, the pattern (\w+)@example\.com captures the part of the email address before @example.com.
Challenge
EasyWrite a function named find_repeated_patterns that takes a text string as input and returns a list of repeated patterns of two characters.
Try it yourself
import re
def find_repeated_patterns(text):
# Write code hereAll lessons in RegEx in Python
1Introduction
Introduction