正则表达式找到这些值?

时间:2015-02-26 16:55:05

标签: python regex

我有这样一句话:

a = "switchport port-security mac-address 000a.1111.2222 vlan 43"

我想将mac和vlan号码粘贴到如下列表中:

["000a.1111.2222","43"]

我认为下面的内容会做到这一点,任何想法?

import re
a = "switchport port-security mac-address 000a.1111.2222 vlan 43"
b = re.findall("([a-fA-F0-9]{4}[\.]){2}([a-fA-F0-9]{4})|(\d+)",a)
print b

3 个答案:

答案 0 :(得分:2)

没有正则表达式,只需使用拆分。

a = "switchport port-security mac-address 000a.1111.2222 vlan 43"

split_list = a.split()
required_info = [split_list[3],split_list[5]]
print required_info
>> ["000a.1111.2222","43"]

答案 1 :(得分:2)

您只需要分组:

>>> a = "switchport port-security mac-address 000a.1111.2222 vlan 43"
>>> import re
>>> re.findall(r'mac-address (.*).*vlan (.*)',a)
[('000a.1111.2222 ', '43')]

答案 2 :(得分:1)

如果您不确定是否可以抓取split ted字符串的索引3和5处的元素,则使用split会有一个稍微不同的解决方案(在这种情况下,它会抓取分别在split"mac-address"之后的"vlan"个元素:

In [1]: a = "switchport port-security mac-address 000a.1111.2222 vlan 43"

In [2]: splitted = a.split()

In [3]: [x for i,x in enumerate(splitted) if i > 0 and splitted[i-1] in ["mac-address", "vlan"]]
Out[3]: ['000a.1111.2222', '43']