我有一些多行文本,每次我的python程序运行时都会改变。我想搜索搜索模式的出现,然后向后查找以:object-group network
开头的第一行示例文本(可能有几千行长):
object-group network CISCO_ROUTER
network-object host 1.1.1.1
network-object object NCPVGW03_10.1.1.2
network-object object NCPVGW04_10.1.1.3
network-object object SGAVGW01_10.2.2.2
network-object object NPLVGW02_10.1.6.2
network-object object NCPVGW02_10.1.1.3
network-object object C1121-8P_FGL2418L267_10.8.8.1
network-object object NDEVGW01_10.6.4.2
network-object object HD999901_192.168.0.3
network-object object ISR4321-FDO21172C94_10.8.8.2
network-object object DMRVGW02_10.1.1.4
object-group network CISCO_SWITCH
network-object host 1.1.1.1
network-object object HD138203_10.198.80.3
network-object object HD165103_10.5.0.1
network-object object HD166207_10.5.1.7
network-object object HD134402_10.194.176.102
network-object object HD137602_10.196.176.102
network-object object HD131603_10.192.240.103
network-object object HD134104_10.194.128.104
network-object object HD166503_10.53.192.103
network-object object HD165510_10.53.64.110
network-object object HD202001_10.33.48.30
network-object object HD132706_10.193.160.106
network-object object HD700041_10.88.64.141
我想找到:network-object object HD700041_10.88.64.141
,然后当我向后看时object-group network
的第一次出现。
我尝试了这个正则表达式搜索模式:(object-group network.+)[wW]+?(?<=HD700041_10.88.64.141)
但结果是:object-group network CISCO_ROUTER
我如何找到第一次出现object-group network CISCO_SWITCH
时,回头看?
可以使用
(?m)^(object-group network.*)(?:n(?!object-group).*)*n.*HD700041_10.88.64.141
参见regex演示。细节:
(?m)^
-行起始(object-group network.*)
-组1:object-group network
在 开头的行(?:n(?!object-group).*)*
- 0或更多不以object-group
字符串开头的行n
- a换行符.*HD700041_10.88.64.141
-除换行符以外的任何零个或多个字符,尽可能多,然后是HD700041_10.88.64.141
文本。
注意最后的141
也可以匹配141000
中的141
。如果您想要匹配特定的141
值,请在末尾添加(?!d)
。