从字符串中提取相同匹配项的多个实例

时间:2018-12-28 02:39:14

标签: python regex

我需要在字符串中提取value的所有模式匹配实例的ssid

interface_info = '''Interface wlan1-cabin-2  
                ifindex 37  
                wdev 0x300000003  
                addr 06:53:1a:4e:07:02  
                ssid SSID3  
                type AP  
                channel 6 (2437 MHz), width: 20 MHz, center1: 2437 MHz  
        Interface wlan1-cabin-1  
                ifindex 36  
                wdev 0x300000002  
                addr 06:53:1a:4e:07:01  
                ssid SSIDTEST2  
                type AP  
                channel 6 (2437 MHz), width: 20 MHz, center1: 2437 MHz  
        Interface wlan1  
                ifindex 7
                wdev 0x300000001  
                addr 06:53:1a:4e:07:00  
                ssid SSID1 
                type AP  
                channel 6 (2437 MHz), width: 20 MHz, center1: 2437 MHz  '''

ssid_regex = re.compile('ssid (\w+)')              
ssid_extract = re.search(ssid_regex,interface_info)

print (ssid_extract)

仅返回第一个匹配项的值。我需要提取每个ssid匹配项的值[SSID3,SSIDTEST2,SSID1}。 SSID3

实际SSID3
预期的[SSID3,SSIDTEST2,SSID1]

1 个答案:

答案 0 :(得分:0)

!/ usr / bin / env python

导入 interface_info ='''
phy#3
        接口wlan1-cabin-1
                ifindex 36
                wdev 0x300000002
                地址06:53:1a:4e:07:01
                ssid SSIDTEST3
                类型AP
                通道6(2437 MHz),宽度:20 MHz,中心1:2437 MHz
        接口wlan1
                ifindex 7
                wdev 0x300000001
                地址06:53:1a:4e:07:00
                ssid SSIDTEST2
                类型AP
                通道6(2437 MHz),宽度:20 MHz,中心1:2437 MHz
phy#2
        接口wlan0
                ifindex 6
                wdev 0x200000001
                地址02:ac:1a:4e:07:00
                ssid SSID1
                类型AP
                频道149(5745 MHz),宽度:80 MHz,中心1:5775 MHz

''' interface_info = re.sub(re.compile('^ \ s +',re.MULTILINE),'',interface_info) ssid_regex = re.compile('ssid(\ w +)') ssid_extract = re.findall(ssid_regex,interface_info [interface_info.index(“ Interface wlan1”):])

打印(ssid_extract) 打印(type(ssid_extract))

print(str(interface_info))