我有一个包含配置的文件。我需要找到一个模式来匹配配置文件中的多行。
基本上,我在寻找以下类型的行:
class-map match-any virtualserver1
description virtualserver1.aaa.com
2 match virtual-address 172.16.211.153 tcp eq https
3 match virtual-address 172.16.211.153 tcp eq https
class-map match-any virtual-server2
2 match virtual-address 172.16.211.154 tcp eq http
class-map match-any vip-helloworld
description vs-yyy.com
class-map match-any vip-myvirtualServer在文件中,块如下:
class-map match-any virtualserver1
description virtualserver1.aaa.com
2 match virtual-address 172.16.211.153 tcp eq https
3 match virtual-address 172.16.211.153 tcp eq https稍后,我需要获得虚拟服务器的名称:如果存在virtualserver1 description (virtualserver1.aaa.com),如果存在多个虚拟地址和端口(172.16.211.153和https),则需要多个虚拟地址和端口。
我尝试了各种组合,试图匹配块,但没有成功。
import re
fh = open('config_file.txt')
fileData = fh.read()
vipData = re.findall('^class-map match-.*\n.+', fileData,re.MULTILINE)
finalList = sorted(set(vipData))
i = 1
for data in finalList:
print str(i) +" "+ str(data)
i = i + 1这只给了我第一行和第二行作为所有配置的输出。
我应该使用什么模式来匹配所有的块?
发布于 2015-02-26 21:32:18
re.findall(r'(?<=class-map match-any).*?(?=class-map match-any|$)', my_str, re.DOTALL)Regex 文档:
(?=...)与...匹配,但不使用的任何字符串。这被称为前瞻性断言。
如果字符串中的当前位置前面有一个以当前位置结束的...匹配,则...匹配。这被称为一个正向后断言。
使用$,所以最后一次匹配也被捕获。
发布于 2015-02-26 21:44:39
好的,,如果您的块不能有超过2‘match’‘es,您可以尝试使用这个正则表达式:
class\-map\s+match\-any\s+(?P<servername>[\w-]+)(?:\s*description\s*(?P<description>[\w\.-]+))?(?:\s*\d+\s+match\s*virtual-address\s*(?P<IP>\d+\.\d+\.\d+\.\d+)\s+[^\r\n]*(?P<HTTP1>https?))?(?:\s*\d+\s+match\s*virtual-address\s*(?P<IP2>\d+\.\d+\.\d+\.\d+)\s+[^\r\n]*(?P<HTTP2>https?))?这些指定的组将保存相应的数据:
servername
description
IP
HTTP1
HTTP2见这里的演示。
import re
p = re.compile(ur'class\-map\s+match\-any\s+(?P<servername>[\w-]+)(?:\s*description\s*(?P<description>[\w\.-]+))?(?:\s*\d+\s+match\s*virtual-address\s*(?P<IP>\d+\.\d+\.\d+\.\d+)\s+[^\r\n]*(?P<HTTP1>https?))?(?:\s*\d+\s+match\s*virtual-address\s*(?P<IP2>\d+\.\d+\.\d+\.\d+)\s+[^\r\n]*(?P<HTTP2>https?))?', re.MULTILINE | re.DOTALL)
str = u"YOUR_STRING"
re.findall(p, str)https://stackoverflow.com/questions/28752331
复制相似问题