I am trying to remove text that is within parentheses (along with the parentheses themselves) but am having trouble with the scenario where there are parentheses within parentheses. This is the method I am using (in Ruby):
sentence.gsub(/\(.*?\)/, "")
and that works fine until I have a sentence such as:
"This is (a test (string))"
Then the above chokes. Anyone have any idea how to do this? I am completely stumped.
If you want to remove the [] and the () you can use this code: >>> import re >>> x = "This is a sentence. (once a day) [twice a day]" >>> re.
Method 1: We will use sub() method of re library (regular expressions). sub(): The functionality of sub() method is that it will find the specific pattern and replace it with some string. This method will find the substring which is present in the brackets or parenthesis and replace it with empty brackets.
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.
One approch is to replace the parenthetical groups from the inside out:
x = string.dup
while x.gsub!(/\([^()]*\)/,""); end
x
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