Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing text within parentheses (parentheses within parentheses prob)

Tags:

string

regex

ruby

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.

like image 814
TenJack Avatar asked Dec 23 '09 02:12

TenJack


People also ask

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. (once a day) [twice a day]" >>> re.

How do you remove content inside brackets without removing brackets in Python?

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.

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

One approch is to replace the parenthetical groups from the inside out:

x = string.dup
while x.gsub!(/\([^()]*\)/,""); end
x
like image 106
glenn mcdonald Avatar answered Oct 04 '22 17:10

glenn mcdonald