我正在使用 parsimonious(python PEG 解析器库)来解析如下所示的文本:
text = """
block block_name_0
{
foo
}
block block_name_1
{
bar
}
"""
它是一系列具有简单正文要求(必须是字母数字)的块组成整个文本。这是语法:
grammar = Grammar(r"""
file = block+
block = _ "block" _ alphanum _ start_brace _ block_body _ end_brace _
block_body = alphanum+
alphanum = ~"[_A-z0-9]+"
_ = ~"[\\n\\s]*"
start_brace = "{"
end_brace = "}"
""")
print (grammar.parse(text))
我遇到的问题是,如果在第一个块之后的任何块中存在解析错误,我会收到一条无用的错误消息。举个例子,考虑以下文本:
text = """
block block_name_0
{
!foo
}
block block_name_1
{
bar
}
"""
这给出了一个有用的错误消息:
[omitted stack trace]
File "/lib/parsimonious/expressions.py", line 127, in match
raise error
parsimonious.exceptions.ParseError: Rule 'block_body' didn't match at '!foo
}
但是,如果我有以下文字:
text = """
block block_name_0
{
foo
}
block block_name_1
{
!bar
}
"""
我收到此错误:
File "/lib/parsimonious/expressions.py", line 112, in parse
raise IncompleteParseError(text, node.end, self)
parsimonious.exceptions.IncompleteParseError: Rule 'file' matched in its entirety, but it didn't consume all the text. The non-matching portion of the text begins with 'block block_name_1
{' (line 7, column 1).
看起来它与序列的第一个实例(第一个块)匹配,但是当它在第二个块上失败时,它不会将整个事情视为失败,这就是我想要它做的。我希望它给我一个与块 0 类似的错误,这样我就可以确切地知道该块出了什么问题,而不仅仅是无法解析整个块。
任何帮助将不胜感激!