Sometimes, we want to extract part of a regex match with Python.
In this article, we’ll look at how to extract part of a regex match with Python.
How to extract part of a regex match with Python?
To extract part of a regex match with Python, we can use the := operator.
For instance, we write
pattern = '<title>(.*)</title>'
text = '<title>hello</title>'
if match := re.search(pattern, text, re.IGNORECASE):
title = match.group(1)
to call re.searcg with the pattern to find the pattern in the text.
We use re.IGNORECASE to find case insensitive matches.
Then we get the match object by using the := with the results returned by re.search.
And we call match.group to find the match for the capturing group.
Conclusion
To extract part of a regex match with Python, we can use the := operator.