Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove text within parentheses with a regex?

Tags:

python

regex

perl

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.

like image 926
Technical Bard Avatar asked Mar 12 '09 18:03

Technical Bard


People also ask

How do I remove parentheses from a string?

Using the replace() Function to Remove Parentheses from String in Python. In Python, we use the replace() function to replace some portion of a string with another string. We can use this function to remove parentheses from string in Python by replacing their occurrences with an empty character.

How do I get rid of text between parentheses in Python?

If you want to remove the [] and the () you can use this code: >>> import re >>> x = "This is a sentence.

Can you use parentheses in regex?

By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex. Only parentheses can be used for grouping.

How do I remove a string within a bracket in Python?

The easiest way to get rid of brackets is with a regular expression search using the Python sub() function from the re module. We can easily define a regular expression which will search for bracket characters, and then using the sub() function, we will replace them with an empty string.


1 Answers

s/\([^)]*\)// 

So in Python, you'd do:

re.sub(r'\([^)]*\)', '', filename) 
like image 178
Can Berk Güder Avatar answered Oct 11 '22 17:10

Can Berk Güder