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 there
module 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 replace a certain group using Python regex?
- How to match a UUID using Python regex?
- How to match whitespace in Python regex?
- How to replace in a file using Python regex?
- How to perform a zero length match with Python Regex?
- How to replace all using Python regex?
- How to match a hex number with regex in Python?
- How to match a plus sign in Python regex?
- How to match a float with regex in Python?
- How to regex match excluding a character in Python?
See more codes...