Give capture groups readable names and refer to prior groups.
How It Works
(?P<name>...) defines a named group, and (?P=name) checks that a later section repeats the same matched text. Naming groups makes extraction less fragile when patterns change.
Step-by-Step Example
import re
pattern = re.compile(r'(?P<word>\w+)\s+(?P=word)')
matched_text = pattern.search('go go now')
print(matched_text.group('word') if matched_text else None)
Understanding the Example
- The expression "re.compile(r'(?P<word>\\w+)\\s+(?P=word)')" supplies the value stored as 'pattern'. This value is then used or checked by the later statements.
- The expression "pattern.search('go go now')" supplies the value stored as 'matched_text'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
go
Where This Fits in a Real Program
Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.
Practice: Try It Yourself
Backreferences can increase matching costs for complex untrusted strings.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Confusing a backreference with a repeated pattern that can match different text.
- Detect duplicate adjacent words in a sentence.
Key Takeaways
- Give capture groups readable names and refer to prior groups.
- (?P<name>...) defines a named group, and (?P=name) checks that a later section repeats the same matched text.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.