How can I remove text within parentheses with a regex?

Technical Bard picture Technical Bard · Mar 12, 2009 · Viewed 132.2k times · Source

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

Can Berk Güder picture Can Berk Güder · Mar 12, 2009
s/\([^)]*\)//

So in Python, you'd do:

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