Categories
Python Answers

How to extract part of a regex match with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *