Technical Bard Technical Bard - 1 year ago 72
Python Question

How can I remove text within parentheses with a regex?

I'm trying to handle a bunch of files, and I need to alter then to remove extraneous information in the filenames; notably, I'm trying to remove text inside parentheses. For example:

filename = "Example_file_(extra_descriptor).ext"

and I want to regex a whole bunch of files where the parenthetical expression might be in the middle or at the end, and of variable length.

What would the regex look like? Perl or Python syntax would be preferred.

Answer Source

So in Python, you'd do:

re.sub(r'\([^)]*\)', '', filename)