I wish to parse a string representing a boolean expression. The following code is based on many examples and uses pyparsing’s operatorPrecedence helper.
The problem is that it I would like the code to raise an exception when the string cannot be sensibly parsed. As it stands, many invalid expressions just pass quietly and the wrong expression is returned.
import pyparsing
_A = pyparsing.Literal('A')
_B = pyparsing.Literal('B')
bool_operand = pyparsing.Or((_A, _B))
precedence_list = [("NOT", 1, pyparsing.opAssoc.RIGHT),
("AND", 2, pyparsing.opAssoc.LEFT),
("OR", 2, pyparsing.opAssoc.LEFT),]
bool_parser = pyparsing.operatorPrecedence(bool_operand, precedence_list)
print bool_parser.parseString('A OR B OR NOT A') # A valid string
print bool_parser.parseString('A NOT AND B') # an invalid string
This outputs:
[['A', 'OR', 'B', 'OR', ['NOT', 'A']]]
['A']
So the first string works, but the second string does not raise an exception as desired.
Any ideas how I can do this? I’m not particularly familiar with pyparsing, so I could have missed something there.
Change your definitions of A_ and B_ to use the
Keywordclass instead of theLiteralclass.Also, when you call parseString, add
parseAll=Trueso that you force the entire input to be parsed.