Pyparsing:dblQuotedString 在 nestedExpr 中以不同方式解析

Pyparsing: dblQuotedString parsing differently in nestedExpr

我正在研究一种语法来解析搜索查询(不是评估它们,只是将它们分解成组成部分)。现在我正在使用 nestedExpr,只是为了获取每个术语的不同 'levels',但如果术语的第一部分用双引号引起来,我似乎遇到了问题。

语法的简单版本:

QUOTED = QuotedString(quoteChar = '“', endQuoteChar = '”', unquoteResults = False).setParseAction(remove_curlies)
WWORD = Word(alphas8bit + printables.replace("(", "").replace(")", ""))
WORDS = Combine(OneOrMore(dblQuotedString | QUOTED | WWORD), joinString = ' ', adjacent = False)
TERM = OneOrMore(WORDS)
NESTED = OneOrMore(nestedExpr(content = TERM))

query = '(dog* OR boy girl w/3 ("girls n dolls" OR friends OR "best friend" OR (friends w/10 enemies)))'

呼叫 NESTED.parseString(query) returns:

[['dog* OR boy girl w/3', ['"girls n dolls"', 'OR friends OR "best friend" OR', ['friends w/10 enemies']]]]

第一个 dblQuotedString 实例与同一嵌套的术语的其余部分分开,第二个 dblQuotedString 实例不会出现这种情况,如果引用也不会出现bit 是一个 QUOTED 实例(带有弯引号)而不是 dblQuotedString 带有直引号。

dblQuotedString 有什么我遗漏的特别之处吗?

注意:我知道 operatorPrecedence 可以像这样分解搜索词,但我对可以分解的内容有一些限制,所以我正在测试是否可以使用 nestedExpr在这些限制内工作。

nestedExpr 采用可选的关键字参数 ignoreExpr,以采用 nestedExpr 应该用来忽略将被解释为嵌套开启符或关闭符的表达式,以及默认值是pyparsing的quotedString,定义为sglQuotedString | dblQuotedString。这是为了处理像这样的字符串:

(this has a tricky string "string with )" )

由于默认 ignoreExprquotedString,引号中的 ')' 不会被误解为右括号。

但是,您的 content 参数也匹配 dblQuotedString。前导引号字符串由 nestedExpr 通过跳过可能包含“()”的引号字符串在内部匹配,然后匹配您的内容,这也匹配引号字符串。您可以使用 NoMatch:

来抑制 nestedExpr 的忽略表达式
NESTED = OneOrMore(nestedExpr(content = TERM, ignoreExpr=NoMatch()))

现在应该给你:

[['dog* OR boy girl w/3',
 ['"girls n dolls" OR friends OR "best friend" OR', ['friends w/10 enemies']]]]

您可以在 https://pythonhosted.org/pyparsing/pyparsing-module.html#nestedExpr

找到更多详细信息和示例