Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python string manipulation

I have a string s with nested brackets: s = "AX(p>q)&E((-p)Ur)"

I want to remove all characters between all pairs of brackets and store in a new string like this: new_string = AX&E

i tried doing this:

p = re.compile("\(.*?\)", re.DOTALL)
new_string = p.sub("", s)

It gives output: AX&EUr)

Is there any way to correct this, rather than iterating each element in the string?

like image 426
Jay Avatar asked May 01 '11 06:05

Jay


2 Answers

Another simple option is removing the innermost parentheses at every stage, until there are no more parentheses:

p = re.compile("\([^()]*\)")
count = 1
while count:
    s, count = p.subn("", s)

Working example: http://ideone.com/WicDK

like image 100
Kobi Avatar answered Oct 20 '22 19:10

Kobi


You can just use string manipulation without regular expression

>>> s = "AX(p>q)&E(qUr)"
>>> [ i.split("(")[0] for i in s.split(")") ]
['AX', '&E', '']

I leave it to you to join the strings up.

like image 23
ghostdog74 Avatar answered Oct 20 '22 17:10

ghostdog74