2

I have to split a string into a list of substrings according to the criteria that all the parenthesis strings should be split .

Lets say I have (9+2-(3*(4+2))) then I should get (4+2), (3*6) and (9+2-18).

The basic objective is that I learn which of the inner parenthesis is going to be executed first and then execute it.

Please help....


It would be helpful if you could suggest a method using re module. Just so this is for everyone it is not homework and I understand Polish notation. What I am looking for is using the power of Python and re module to use it in less lines of code.

Thanks a lot....

  • is your grammar limited to () numbers and basic operators +-/*? – kevpie Dec 06 '10 at 14:38
  • In case you want to parse this, and not just extract strings: You cannot possibly parse nested parens (or nested anything, for that matter) with regexes (... alone; regexes have their part in tokenization). You need a full parser to do this properly. –  Dec 06 '10 at 15:45

4 Answers4

4

The eval is insecure, so you have to check input string for dangerous things.

>>> import re
>>> e = "(9+2-(3*(4+2)))"
>>> while '(' in e:
...     inner = re.search('(\([^\(\)]+\))', e).group(1)
...     e = re.sub(re.escape(inner), eval('str'+inner), e)
...     print inner,
... 
(4+2) (3*6) (9+2-18)
Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153
1

Try something like this:

import re
a = "(9+2-(3*(4+2)))"
s,r = a,re.compile(r'\([^(]*?\)')
while('(' in s):
    g = r.search(s).group(0)
    s = r.sub(str(eval(g)),s)
    print g
    print s
kzh
  • 19,810
  • 13
  • 73
  • 97
  • Could you tell if my explaination of the matching string is correct that it will match the string if it starts from the beginning and goes through the ( and atleast one of them should be there , then the part after the ( is taken into g ?? –  Dec 06 '10 at 19:27
0

This sounds very homeworkish so I am going to reply with some good reading that might lead you down the right path. Take a peek at http://en.wikipedia.org/wiki/Polish_notation. It's not exactly what you want but understanding will lead you pretty close to the answer.

Andrew White
  • 52,720
  • 19
  • 113
  • 137
0

i don't know exactly what you want to do, but if you want to add other operations and if you want to have more control over the expression, i suggest you to use a parser

http://www.dabeaz.com/ply/ <-- ply, for example

Ant
  • 5,151
  • 2
  • 26
  • 43