Home >Backend Development >Python Tutorial >How Can I Capture Multiple Subpatterns in a Python Regex?
Capturing Multiple Subpatterns in Python Regex
While attempting to match portions of an email address, specifically where there are multiple occurrences of a pattern like .(w ), you've encountered an issue where only the last match is being captured.
Using the Python re module, this repeated capture is not directly supported. However, an alternative method is to match the entire string initially and then split the subpatterns later. Here's an example of how you can achieve this:
import re text = '[email protected]' pattern = r'([.\w]+)@((\w+)(\.\w+)+)' match = re.match(pattern, text) # Split the captured subpattern (e.g., '.something.edu.tr') into a list sub_patterns = match.group(2).split('.')
In this approach, we've first matched the entire email address and then used Python's split() method to separate the subpatterns. This provides a simple and readable solution for handling such patterns.
The above is the detailed content of How Can I Capture Multiple Subpatterns in a Python Regex?. For more information, please follow other related articles on the PHP Chinese website!