我有类似下面的文件,它是config的一部分,其中包含了ruledefs的引用(即rd-6)。除了规则库和ruledefs名称之外,配置文件结构看起来始终相同。这部分是rulebase-definition (对于这个问题,这也是我的RB-finitions.txt)
##Rulebase-definition
rulebase bb
action priority 6 dynamic-only ruledef rd-6 charging-action throttle monitoring-key 1
action priority 7 dynamic-only ruledef rd-7 charging-action p2p_Drop
action priority 139 dynamic-only ruledef rd-8 charging-action p2p_Drop monitoring-key 1
#exit下面是ruledef-definition示例(这也是我在这个问题中寻找的输出)
##Ruledef-definition
ruledef rd-8
ip server-ip-address range host-pool BB10_RIM_1
ip server-ip-address range host-pool BB10_RIM_2
#exit
ruledef rd-3
ip any-match = TRUE
#exit我能够匹配raw_input()提供的特定规则库名称(具有规则库定义),并将其保存到文件RB-finitions.txt,如您在上面看到的。此外,我还能够匹配RB-finitions.txt中的ruledef名称(但仅匹配名称),并将其存储在ruledef_list中,如下所示
RDFile = open('RB-definitions.txt')
txt2 = RDFile.read()
ruledef_list = []
for match2 in re.findall((?<=ruledef)((?:.|\n)*?)(?=charging-action), txt2):
print match2 +"\n"
ruledef_list.append(match2)但是当我必须匹配上面所示的ruledef-defitnition中的特定ruledef时,我总是失败。ruledef word始终排在行的第一位
start_tag = '^ruledef ' #additional space char
content = '((?:.|\n)*?)'
end_tag = '#exit'
for RD_name in ruledef_list:
print RD_name
for match in re.findall(start_tag + RD_name + content + end_tag, txt):
print match + end_tag + "\n" 我尝试了'^ruledef ','^ruledef\s+‘,甚至'(ruledef )\b',但这些都不起作用。我必须计算第一个单词,因为如果不是,我也会匹配从"ruledef“开始的rulebase-defitnition的一部分。
如何匹配行中定义的第一个单词与下一个"#exit“之间的所有内容?因此,作为输出,我可以得到以下内容
ruledef rd-8
ip server-ip-address range host-pool BB10_RIM_1
ip server-ip-address range host-pool BB10_RIM_2
#exit
ruledef rd-3
ip any-match = TRUE
#exit为了更好地理解,请在此处找到包含示例配置的完整脚本http://pastebin.com/q3VUeAdh
发布于 2013-07-01 00:04:02
您缺少多行模式。否则,^只在整个字符串的开头匹配。此外,您可以通过使用单行/dotall模式(该模式使.匹配任何字符)来避免(?:.|\n):
start_tag = r'^ruledef ' #additional space char
content = r'(.*?)'
end_tag = r'#exit'
...
for match in re.findall(start_tag + RD_name + content + end_tag, txt, re.M|re.S):
...请注意,这将为您提供ruledef的内容(即,仅与content部分匹配的内容-无ruledef、无名称、无#exit). If this is not what you want, simply remove the parentheses in内容`:
...
content = r'.*?'
...顺便说一句,使用负前视可能比使用不贪婪的量词更有效(但它不必-如果速度对您来说很重要,请分析一下这一点):
...
content = r'(?:(?!#exit).)*'
...最后,请注意我如何对所有正则表达式模式使用原始字符串。这在Python中是一个很好的实践--否则你可能会在复杂的转义模式中遇到问题(即,你必须对某些东西进行双重转义)。
https://stackoverflow.com/questions/17391943
复制相似问题