python-regexHow to use a regex capture group in Python?
Regex capture groups are used to group parts of a regular expression together so that they can be referenced later. In Python, capture groups are accessed using the group() method of the Match object.
Example code
import re
text = "The cat in the hat"
match = re.search(r"(\w+) in the (\w+)", text)
if match:
print(match.group(1))
print(match.group(2))
Output example
cat
hat
Code explanation
import re: This imports theremodule which contains the functions needed to use regular expressions in Python.text = "The cat in the hat": This creates a string variable containing the text to be searched.match = re.search(r"(\w+) in the (\w+)", text): This uses there.search()function to search for a pattern in the text. The pattern is enclosed in parentheses to create two capture groups.if match:: This checks if a match was found.print(match.group(1)): This prints the first capture group.print(match.group(2)): This prints the second capture group.
Helpful links
More of Python Regex
- How to match whitespace in Python regex?
- How to get a group from a regex in Python?
- How to perform a zero length match with Python Regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to validate an IP using Python regex?
- How to replace in a file using Python regex?
- How to use word boundaries in Python Regex?
- How to make a case insensitive match with Python regex?
- How to match a question mark in Python regex?
- How to match a URL path using Python regex?
See more codes...