对于下面显示的脚本语言(Backus–Naur形式),我如何使用正则表达式描述语法(或进行pyparsing更好?):
<root> := <tree> | <leaves>
<tree> := <group> [* <group>]
<group> := "{" <leaves> "}" | <leaf>;
<leaves> := {<leaf>;} leaf
<leaf> := <name> = <expression>{;}
<name> := <string_without_spaces_and_tabs>
<expression> := <string_without_spaces_and_tabs>
脚本示例:
{
stage = 3;
some.param1 = [10, 20];
} *
{
stage = 4;
param3 = [100,150,200,250,300]
} *
endparam = [0, 1]
我使用python re.compile并希望将所有内容分成组,如下所示:
[ [ 'stage', '3'],
[ 'some.param1', '[10, 20]'] ],
[ ['stage', '4'],
['param3', '[100,150,200,250,300]'] ],
[ ['endparam', '[0, 1]'] ]
更新:我发现pyparsing是比regex更好的解决方案。
通过Pyparsing,您可以简化其中一些构造
leaves :: {leaf} leaf
只是
OneOrMore(leaf)
因此,pyparsing中BNF的一种形式将类似于:
from pyparsing import *
LBRACE,RBRACE,EQ,SEMI = map(Suppress, "{}=;")
name = Word(printables, excludeChars="{}=;")
expr = Word(printables, excludeChars="{}=;") | quotedString
leaf = Group(name + EQ + expr + SEMI)
group = Group(LBRACE + ZeroOrMore(leaf) + RBRACE) | leaf
tree = OneOrMore(group)
我添加了quotedString作为替代的expr,以防万一您想要包含确实被排除的字符之一的东西。并且在叶子和组周围添加组将保持支撑结构。
不幸的是,您的样本并不完全符合此BNF:
在空间[10, 20]
和[0, 1]
让他们无效exprs
有些叶子没有终止;
小号
孤单*
字符-???
此示例使用上述解析器成功解析:
sample = """
{
stage = 3;
some.param1 = [10,20];
}
{
stage = 4;
param3 = [100,150,200,250,300];
}
endparam = [0,1];
"""
parsed = tree.parseString(sample)
parsed.pprint()
给予:
[[['stage', '3'], ['some.param1', '[10,20]']],
[['stage', '4'], ['param3', '[100,150,200,250,300]']],
['endparam', '[0,1]']]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句