我正在解析路由器的配置文件。通常,我将正则表达式与命名组一起使用,并为此目的: https://regex101.com/r/EcyPeh/5 在此示例中,我使用名为“ svcindent”的组+关键字“ exit”作为服务配置上下文的缩进。
如何用pyparsing做同样的事情?
以下源代码中有SkipTo(intend + Keyword(“ exit”))。我尝试将其用作de-indent。但是它匹配各种空格,这就是为什么它与“ exit”关键字匹配的原因stp上下文。
from pyparsing import *
data = """
vpls 82 customer 700 i-vpls create
service-mtu 9040
send-flush-on-failure
propagate-mac-flush
stp
shutdown
exit
sap 2/2/8:0.1 create
ingress
qos 13
queue-override
queue 1 create
cbs 1000
rate 10240 cir 10240
exit
exit
exit
exit
spoke-sdp 4:82 endpoint "vpls-82-uplink" create
stp
shutdown
exit
precedence primary
no shutdown
exit
spoke-sdp 6:82 endpoint "vpls-82-uplink" create
stp
shutdown
exit
no shutdown
exit
mac-move
no shutdown
exit
no shutdown
exit
vpls 121 customer 700 i-vpls create
service-mtu 9040
send-flush-on-failure
propagate-mac-flush
stp
shutdown
exit
sap 2/2/9:900 create
ingress
qos 13
queue-override
queue 1 create
cbs 3000
rate 10240 cir 10240
exit
exit
exit
exit
spoke-sdp 4:121 endpoint "vpls-121-uplink" create
stp
shutdown
exit
precedence primary
no shutdown
exit
spoke-sdp 6:121 endpoint "vpls-121-uplink" create
stp
shutdown
exit
no shutdown
exit
mac-move
no shutdown
exit
no shutdown
exit
vpls 1986692 customer 555 i-vpls create
service-mtu 9040
send-flush-on-failure
propagate-mac-flush
stp
shutdown
exit
sap 2/2/9:130 create
ingress
qos 13
queue-override
queue 1 create
cbs 1000
rate 10240 cir 10240
exit
exit
exit
exit
spoke-sdp 4:1986692 endpoint "vpls-1986692-uplink" create
stp
shutdown
exit
precedence primary
no shutdown
exit
spoke-sdp 6:1986692 endpoint "vpls-1986692-uplink" create
stp
shutdown
exit
no shutdown
exit
mac-move
no shutdown
exit
no shutdown
exit
"""
indent = LineStart() + OneOrMore(White(' ', exact=4))
deident = matchPreviousExpr(indent) + Keyword("exit")
svc_id = Word(nums)
customer_id = Word(nums)
sp = White(' ', exact=1)
svc_stmt = Combine(indent("int_s") + Keyword("vpls") + sp + svc_id + sp + Keyword("customer") + sp + customer_id + SkipTo(Keyword("create"), include=True)) + Combine(SkipTo(deident, include=True))
svc_stmt.leaveWhitespace()
parseTree = svc_stmt.searchString(data)
parseTree.pprint()
Result:
[[' vpls 82 customer 700 i-vpls create',
'\n'
' service-mtu 9040\n'
' send-flush-on-failure\n'
' propagate-mac-flush\n'
' stp\n'
' shutdown\n'
' exit'],
[' vpls 121 customer 700 i-vpls create',
'\n'
' service-mtu 9040\n'
' send-flush-on-failure\n'
' propagate-mac-flush\n'
' stp\n'
' shutdown\n'
' exit'],
[' vpls 1986692 customer 555 i-vpls create',
'\n'
' service-mtu 9040\n'
' send-flush-on-failure\n'
' propagate-mac-flush\n'
' stp\n'
' shutdown\n'
' exit']]