Categories
Python Answers

How to use regular expression to return text between parenthesis with Python?

Spread the love

Sometimes, we want to use regular expression to return text between parenthesis with Python.

In this article, we’ll look at how to use regular expression to return text between parenthesis with Python.

How to use regular expression to return text between parenthesis with Python?

To use regular expression to return text between parenthesis with Python, we call re.search with the r'\((.*?)\)' regex string.

For instance, we write

import re

s = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
match = re.search(r'\((.*?)\)', s).group(1)

to call re.search with the r'\((.*?)\)' regex string to and string s to find the parts of string s that has the content between parentheses.

And then we call group with 1 to get the 2nd capturing group.

Conclusion

To use regular expression to return text between parenthesis with Python, we call re.search with the r'\((.*?)\)' regex string.

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 *