首页 > 解决方案 > Python正则表达式在多行中编译匹配

问题描述

多行正则表达式搜索以构建列表

我曾尝试使用带有特定模式的 re.compile 以及标志 re.MULTILINE 但它不起作用。

rx_dict = {
    'user_db_pppoe' : re.compile(r"sap-session-limit\s\d{5}\n\s+(?P<USERDB_P>.*)\w+")
}

with open('test_input.txt', 'r') as file_object:
    if key == 'user_db_pppoe':
        print(match)

配置:

                    pppoe
                        policy "pppoe-change-mtu"
                        session-limit 32767
                        sap-session-limit 32767
                        user-db "LAC-l2tp-DXB"
                        no shutdown
                    exit
                exit

但是多行不接受 re 模块

rx_dict = {
    'user_db_pppoe' : re.compile(r"sap-session-limit\s\d{5}\n\s+(?P<USERDB_P>.*)\w+" , re.MULTILINE)}

我要求在此处匹配 user-db 值“LAC-l2tp-DXB”,它遵循 sap-session-limit 值。

标签: python-3.x

解决方案


您的代码存在一些问题,这里有一种注释方式(假设您的问题中的“配置”是test_input.txt内容:

### specify both substring you want to find in the line
rx_dict = {
    'user_db' : re.compile(r"LAC-l2tp-DXB"),
    'sap_session_limit' : re.compile(r"sap-session-limit")
}

### open the file
with open('test_input.txt', 'r') as file_object:
    ### start a counter to remember line number
    line_count = 0
    ### open loop over the file line (you have to use string for regex, nt as you did in example on file_object)
    for line in file_object :
        ### if found first ocurrence remember line number of first match
        if (rx_dict['sap_session_limit'].search(line)) :
            sap_line = line_count
        ### if found second one AND the line is the next to first ocurrence find
        if (rx_dict['user_db'].search(line) and line_count == (sap_line + 1)) :
            ### ... do what you want to do ...
            print(line)            
        ### increase counter
        line_count += 1

这可以满足您的要求。另请注意,您使用了错误的字典键参考,请查看文档以正确使用键和值。


推荐阅读