1

我有以下片段,其中包含来自 pyparsing 解析器的递归语句:

def parse_query(querystr):
    # <<other parsing stuff>>
    queryexpression = querycondition + ZeroOrMore(Word("and") + querycondition)
    try:
        return queryexpression.parseString(querystr)
    except ParseException as e:
        logger.debug("Error parsing '{0}': \n {1}".format(querystr, e))
        return None

当我提供这个查询时:

tokens = parse_query("HR:EE > -28.9 and BL:AA = 0 THISISNOTAND KLAS:TT eq true")
print(tokens)

它产生:

[['HR', ':', 'EE', '>', '-28.9'], 'and', ['BL', ':', 'AA', '=', '0']]

只是默默地跳过最后一个条件。没有抛出异常。

如何捕获此字符串中的错误?

4

1 回答 1

1

queryexpression = querycondition + ZeroOrMore(Word("and") + querycondition)

不是解析整行所必需的ZeroOrMore就是这个意思。当它遇到不符合定义的东西时它会停止。它总是会成功,因为“零”是嵌套表达式匹配次数的有效选项。

如果您想一直解析到行尾,那么您将需要一个明确要求的表达式,例如通过添加+ LineEnd.

Lines are not "special" unless you make them so. A parsing expression, by default, expects to match a prefix of the input, not the entire input, because you always might want to use another expression to parse the next bit.

于 2011-11-03T14:14:16.333 回答