I have been fighting to get pyparsing for hours now, even if what I want to do is basic.
I would like to parse expression based on "or" and "and".
Example that is working great:
s = "((True and True) or (False and (True or False)) or False)"
parens = pyparsing.nestedExpr( '(', ')', content=pyparsing.Word(pyparsing.alphanums) | ' or ' | " and " )
r = parens.parseString(s)[0]
print parens.parseString(s)[0]
which prints:
[['True', 'and', 'True'], 'or', ['False', 'and', ['True', 'or', 'False']], 'or', 'False']
Now, I would to the same, but instead of "True" and "False", use any possible string that contains neither " and " or " or "
I was expecting the following to work fine:
s = "( c>5 or (p==4 and c<4) )"
parens = pyparsing.nestedExpr( '(', ')', content=pyparsing.Word(' or ') | ' and ' )
print parens.parseString(s)[0]
but this throws an exception :
pyparsing.ParseException: Expected ")" (at char 2), (line:1, col:3)
I have been fighting quite a lot, mostly tryign to change the content, but no success.
Any idea ?
---- Note
I ended up using my own code rather than pyparsing.
I guess the question nevertheless remains valid to for those still interesting in pyparsing.
Here the code I use now:
def parse(s,container):
my_array = []
i = 0
while i < len(s):
if s[i]!="(" and s[i]!=")":
my_array.append(s[i])
i+=1
elif s[i]=="(" :
end_index = parse(s[i+1:],my_array)
i += end_index+1
elif s[i]==")":
container.append(my_array)
return i+1
return my_array
example :
s = "(True and True) or (False and (True or False)) or False"
to_broaden = ("(",")")
for tb in to_broaden : s = s.replace(tb," "+tb+" ")
s = s.split()
print parse(s,[])
result :
[['True', 'and', 'True'], 'or', ['False', 'and', ['True', 'or', 'False']], 'or', 'False']