输出不是预期的。我希望在“系统”目录下打印有关“系统”的所有差异,并在“接口”目录下打印与“接口”相关的所有差异。即使我有声明要抓住它,“ {...}”也不会打印。代码如下:
import re
template_list = ['system','interfaces']
directory = '/templates/juniper/junos/vfirewall/'
diff = """[edit system name-server]
8.8.8.8 { ... }
+ 4.4.4.4;
[edit interfaces ge-0/0/0 unit 0 family inet]
+ address 10.20.30.10/24;
- address 10.50.30.10/24;
[edit interfaces]
+ ge-0/0/1 {
+ unit 2 {
+ family inet {
+ address 10.50.80.10/24;
+ }
+ }
+ }""".splitlines()
for template in template_list:
print("{}{}".format(directory,template))
for line in diff:
if(re.match('\[edit\s({})'.format(template),line)):
print('{}'.format(line))
elif(re.match('\{ ... \}',line)):
print('{}'.format(line))
elif(re.match('^\-',line)):
print('{}'.format(line))
elif(re.match('^\+',line)):
print('{}'.format(line))
elif(re.match('\[edit\s\w.+',line)):
break
输出给出:
/templates/juniper/junos/vfirewall/system
[edit system name-server]
+ 4.4.4.4;
/templates/juniper/junos/vfirewall/interfaces
>>>
预期输出:
/templates/juniper/junos/vfirewall/system
[edit system name-server]
8.8.8.8 { ... }
+ 4.4.4.4;
/templates/juniper/junos/vfirewall/interfaces
[edit interfaces ge-0/0/0 unit 0 family inet]
+ address 10.20.30.10/24;
- address 10.50.30.10/24;
[edit interfaces]
+ ge-0/0/1 {
+ unit 2 {
+ family inet {
+ address 10.50.80.10/24;
+ }
+ }
+ }
答案 0 :(得分:1)
两个主要问题:
您应该对正则表达式使用原始字符串,以便将转义序列从字面上传递给regexp引擎,而不是作为字符串转义进行处理。
您需要使用re.search()
而不是re.match()
,因为后者仅在字符串的开头匹配(等效于以^
开头的RE)。 / p>
次要问题:.
中的...
应该转义为字面匹配,而-
则不必转义。
工作版本:
import re
template_list = ['system','interfaces']
directory = '/templates/juniper/junos/vfirewall/'
diff = """[edit system name-server]
8.8.8.8 { ... }
+ 4.4.4.4;
[edit interfaces ge-0/0/0 unit 0 family inet]
+ address 10.20.30.10/24;
- address 10.50.30.10/24;
[edit interfaces]
+ ge-0/0/1 {
+ unit 2 {
+ family inet {
+ address 10.50.80.10/24;
+ }
+ }
+ }""".splitlines()
for template in template_list:
print("{}{}".format(directory,template))
for line in diff:
if(re.search(r'\[edit\s({})'.format(template),line)):
print('{}'.format(line))
elif(re.search(r'\{ \.\.\. \}',line)):
print('{}'.format(line))
elif(re.search(r'^-',line)):
print('{}'.format(line))
elif(re.search(r'^\+',line)):
print('{}'.format(line))
elif(re.search(r'\[edit\s\w.+',line)):
break