我尝试使用pyparsing解析以下结构:
{
firewall {
group {
address-group {
address 1.2.3.4
}
address-group {
address 5.6.7.4
}
}
}
}
代码:
from pyparsing import *
LBRACE, RBRACE = map(Suppress, "{}")
prop = Word(printables, excludeChars="{}\"")
numberValue = pyparsing_common.number()
configObject = Forward()
value = Forward()
value << (prop | numberValue | Group(configObject))
memberDef = Group(prop + value)
configMembers = delimitedList(memberDef)
configObject << Dict(LBRACE + Optional(configMembers) + RBRACE)
if __name__ == "__main__":
testdata = """
{
firewall {
group {
address-group {
address 1.2.3.4
}
address-group {
address 1.2.3.4
}
}
}
}
"""
results = configObject.parseString(testdata)
print(results.firewall.group)
它抛出
pyparsing.ParseException:预期&#34;}&#34; (在char 15),(第3行,第9栏)
如果我只有一个address-group
它正在运作:
{
firewall {
group {
address-group {
address 1.2.3.4
}
}
}
}
修改
{
firewall {
group {
address-group {
address 1.2.3.4
}
address-group {
address 5.6.7.4
}
}
}
}
使用configMembers = OneOrMore(memberDef)
代替configMembers = delimitedList(memberDef)
解决
我也需要解析它(请注意name
之后的adress-group
:
{
firewall {
group {
address-group name1 {
address 1.2.3.4
}
address-group name2 {
address 5.6.7.4
}
}
}
}
答案 0 :(得分:1)
我在两个地址组之间添加了一个逗号,一切正常
{
firewall {
group {
address-group {
address 1.2.3.4
},
address-group {
address 5.6.7.4
}
}
}
}
因此代码是
from pyparsing import *
LBRACE, RBRACE = map(Suppress, "{}")
prop = Word(printables, excludeChars="{}\"")
numberValue = pyparsing_common.number()
configObject = Forward()
value = Forward()
value << (prop | numberValue | Group(configObject))
memberDef = Group(prop + value)
configMembers = delimitedList(memberDef)
configObject << Dict(LBRACE + Optional(configMembers) + RBRACE)
if __name__ == "__main__":
testdata = """
{
firewall {
group {
address-group {
address 1.2.3.4
},
address-group {
address 5.6.7.4
}
}
}
}
"""
results = configObject.parseString(testdata)
print(results.firewall.group)
,输出
[['address-group', [['address', '1.2.3.4']]], ['address-group', [['address',
'5.6.7.4']]]]