## Re: [Pyparsing] Logical operations

 Re: [Pyparsing] Logical operations From: Eike Welk - 2008-06-03 14:12:14 On Tuesday 03 June 2008 09:34, happybrowndog wrote: > Hello... > first of all, thanks for your help in my last post on "Function > parameters that may have brackets" - I solved the problem by going > through the code samples as you stated and the problem is solved > now. > > Now I am having problems with parsing logical operations. > > I have an expression: > calcexpr = operatorPrecedence( w_operand,[(op_sign, 1, > opAssoc.RIGHT),(op_mult, 2, opAssoc.LEFT),(op_div, 2, > opAssoc.LEFT),(op_plus, 2, opAssoc.LEFT),(op_minus, 2, > opAssoc.LEFT),]) > > which parses the following correctly: "(3+6)/5". > > then I have: > boolexpr = Forward() > boolexpr << calcexpr + ("=" ^ ">" ^ "<") + calcexpr + > Optional(("AND" ^ "OR") + boolexpr) > > boolexpr then parses the following correctly: "(3+6)/5 > 1 AND 2 < > 9" > > but returns an error on the following: "((3+6)/5 > 1) AND (2 < 9)" > > ultimately, I would like to be able to parse a statement such as: > "((3+6)/5 > 1) AND ( (2 < 9) OR ( (2+5/12 < 1) AND ( 3 < 4) ) )" > > but of course this would also fail. > > To try to get to my goal, I try adding Optional("(") and > Optional(")") to boolexpr, such as: > > boolexpr << Optional("(") + calcexpr + ("=" ^ ">" ^ "<") + > calcexpr + Optional(")") + Optional(("AND" ^ "OR") + boolexpr) > > but this does not resolve the problem. The brackets are screwing > things up. I think the cause may be related to the same reason I > was having problems previously, but I can't seem to link the two. > > Can you please point me in the right direction? You should should add the additional operators to operatorPrecedence. First define: op_and = Keyword('AND') op_or = Keyword('OR') op_eq = Literal('=') op_lt = Literal('<') op_gt = Literal('>') And then add the following to the call to operatorPrecedence.: (op_and, 2, opAssoc.LEFT), (op_or, 2, opAssoc.LEFT), (op_eq, 2, opAssoc.LEFT), (op_lt, 2, opAssoc.LEFT), (op_gt, 2, opAssoc.LEFT), The "AND" belongs to the same level like multiplication, the 'OR' belongs to '+' and the and the comparison operators '= < >' belong to the end (IMHO). (Everything completely untested.) HTH, Eike.