对 AND/OR 关键字进行 Pyparsing 验证,无需进一步表达

Pyparsing validation on AND/OR keyword without further expression

我有一个支持ANDOR的公式格式:

import pyparsing as pp

# Basic literals.
DOUBLE_QUOTE = pp.Literal('"')
SINGLE_QUOTE = pp.Literal("'")
AND_OR = pp.oneOf("AND OR", True)
CONDITION = pp.oneOf("> < = >= <=")

# Left and right hand sides.
lhs = pp.Word(pp.alphas + pp.alphas8bit + pp.alphanums + "." + "_")
rhs_str = pp.Word(pp.alphas + pp.alphas8bit + pp.alphanums + "." + "_" + "-" + ":")
rhs_num = pp.Word(pp.nums)
rhs = (
    (DOUBLE_QUOTE + rhs_str + DOUBLE_QUOTE)
    | (SINGLE_QUOTE + rhs_str + SINGLE_QUOTE)
    | (rhs_num)
)

# Basic expressions.
# Samples:
# * user.id = 10
# * name = "user" and user.id > 10
one_expr = lhs + CONDITION + rhs
unpack_expr = one_expr + pp.ZeroOrMore(AND_OR + one_expr)

例如:

>>> print(unpack_expr.parseString("a = 10 and b = 2"))
['a', '=', '10', 'AND', 'b', '=', '2']

它工作正常,但是当我在表达式末尾添加另一个 AND/OR 关键字但没有任何进一步的表达式时,它仍然工作正常,但我预计会出现错误:

>>> print(unpack_expr.parseString("a = 10 and b = 2 or"))
['a', '=', '10', 'AND', 'b', '=', '2']

要解决这个问题,您需要使用stringEnd():

import pyparsing as pp# Basic literals.
DOUBLE_QUOTE = pp.Literal('"')
SINGLE_QUOTE = pp.Literal("'")
AND_OR = pp.oneOf("AND OR", True)
CONDITION = pp.oneOf("> < = >= <=")# Left and right hand sides.
lhs = pp.Word(pp.alphas + pp.alphas8bit + pp.alphanums + "." + "_")
rhs_str = pp.Word(pp.alphas + pp.alphas8bit + pp.alphanums + "." + "_" + "-" + ":")
rhs_num = pp.Word(pp.nums)
rhs = (
    (DOUBLE_QUOTE + rhs_str + DOUBLE_QUOTE)
    | (SINGLE_QUOTE + rhs_str + SINGLE_QUOTE)
    | (rhs_num)
)# Basic expressions.
# Samples:
# * user.id = 10
# * name = "user" and user.id > 10
one_expr = lhs + CONDITION + rhs
unpack_expr = one_expr + pp.ZeroOrMore(AND_OR + one_expr) + pp.stringEnd()