我尝试了以下方法:
import re
import sys
config_file = 'config_file.log'
# config_file = sys.argv[1]
with open(config_file) as file_obj:
data_buff = file_obj.read()
mixRegex = re.compile(r'^Interface\s+IP-Address\s+Status.*\n'
r".*\n*",re.MULTILINE)
mix_match = mixRegex.findall(data_buff)
print(mix_match)
以上代码运行以后输出如下:
['Interface IP-Address Status Protocol Vrf-Name\nLoopback0 124.53.16.87 Up Up default \n']
可以看到,已经匹配出来了一部分,但是只能匹配到第二行。
请教一下,
mixRegex = re.compile(r'^Interface\s+IP-Address\s+Status.*\n'
r".*\n*",re.MULTILINE)
这一句应该如何修改才是?
我修改为:
mixRegex = re.compile(r'^Interface\s+IP-Address\s+Status.*\n'
r".*\n*\n.*\n*",re.MULTILINE)
匹配结果就又增加两行,但是我提前也不知道总共有多少行呢。
我修改为以下代码,解决了我的问题:
import re
config_file = 'config_file.log'
with open(config_file) as file_obj:
data_buff = file_obj.read()
mixRegex = re.compile(r'^Interface\s+IP-Address\s+Status.*\n'
r'(^\w+\d+.*\n)+'
r'^RP.*#'
,re.MULTILINE)
mix_match = mixRegex.search(data_buff)
print(mix_match.group())