Python正则表达式搜索字符串

时间:2017-04-14 15:52:53

标签: python regex

我有以下代码:

def ospf_route_type_E2_exists(nbr_output,AS_ext_net_list,net_list):
    match_list=[]
    if type(AS_ext_net_list) is not list:
        AS_ext_net_list=[AS_ext_net_list]
    if type(net_list) is not list:
        net_list=[net_list]
    for ext_net,net in zip(AS_ext_net_list,net_list):
        net_prefix=str(net).rstrip(".0")
        match= re.search(r"O[" "]+E2[" "]+str\(ext_net\)[" "]+\[[0-9]*[0-9]*[0-9]+\/[0-9]+\][" "]+via[" "]+str(net_prefix)",nbr_output)
        match_list.append(match)
    if any(item for item in match_list):
        print "AS External networks properly advertised via correct areas"
        return 1
    else:
        print "AS External networks not properly advertised via correct areas"
        return 0

nbr_ouput将包含以下内容:

show ip route ospf 
O IA 192.168.42.0/24 [110/2] via 192.168.43.4, 00:00:29, FastEthernet0/0
O    192.168.124.0/24 [110/2] via 192.168.43.4, 00:00:29, FastEthernet0/0
    10.0.0.0/24 is subnetted, 1 subnets
O E2    10.1.1.0 [110/1] via 192.168.43.4, 00:00:29, FastEthernet0/0

我想搜索一行:

O E2    10.1.1.0 [110/1] via 192.168.43.4, 00:00:29, FastEthernet0/0

使用我的代码中的匹配行:

 match= re.search(r"O[" "]+E2[" "]+str\(ext_net\)[" "]+\[[0-9]*[0-9]*[0-9]+\/[0-9]+\][" "]+via[" "]+str(net_prefix)",nbr_output)

预期产出:

        print "AS External networks properly advertised via correct areas"
        return 1

我得到的输出:

        print "AS External networks not properly advertised via correct areas"
        return 0

这告诉我我的正则表达式搜索不起作用。请让我知道我做错了什么

1 个答案:

答案 0 :(得分:0)

我用过:

match= re.search(r"O\s+E2\s+"+str(ext_net)+"\s+\[[0-9]+\/[0-9]+\]\s‌​+via\s+"+str(net_pre‌​fix),nbr_output) 

它有效。