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.
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.
If you want to remove the [] and the () you can use this code: >>> import re >>> x = "This is a sentence.
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.
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.
s/\([^)]*\)//
So in Python, you'd do:
re.sub(r'\([^)]*\)', '', filename)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With