如何在regex中找到循环模式

2024-10-04 05:22:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从字符串列表中找到正则表达式模式。特别是想把港口还回去。你知道吗

data = '''348  VLAN0348                         active    Fa4/24, Fa4/26, Gi2/4
349  VLAN0349                         active    Fa6/40, Fa6/43, Fa6/45
350  VLAN0350                         active    Fa6/41, Gi3/40'''.split('\n')

使用这段代码,我可以筛选出第一个字符串,但我需要其余的字符串。你知道吗

FoundPorts = []
if checkVlan in x:
        port = re.search(r'active    (\S*)',x)
            if port != None:
                FoundPorts.append(port.group(1))`

理想情况下我会得到:

FoundPorts = ['Fa4/24','Fa4/26','Gi2/4','Fa6/40','Fa6/43','Fa6/45','Fa6/41','Gi3/40']

Tags: 字符串列表dataifport模式active港口
3条回答

如果您想使用regex路径,下面的regex模式就可以了

>>> re.findall(r"[A-Z][a-z]\d/\d\d?", data)
['Fa4/24', 'Fa4/26', 'Gi2/4', 'Fa6/40', 'Fa6/43', 'Fa6/45', 'Fa6/41', 'Gi3/40']

regex的另一个替代方法是使用fnmatch来处理示例数据

>>> import fnmatch
>>> [elem.rstrip(',') for elem in fnmatch.filter(data.split(),"*/*")]
['Fa4/24', 'Fa4/26', 'Gi2/4', 'Fa6/40', 'Fa6/43', 'Fa6/45', 'Fa6/41', 'Gi3/40']

这不是使用正则表达式,但它应该做到这一点

data = '''348  VLAN0348                         active    Fa4/24, Fa4/26, Gi2/4
349  VLAN0349                         active    Fa6/40, Fa6/43, Fa6/45
350  VLAN0350                         active    Fa6/41, Gi3/40'''

[i.strip(",") for i in data.split() if "/" in i]

输出

['Fa4/24', 'Fa4/26', 'Gi2/4', 'Fa6/40', 'Fa6/43', 'Fa6/45', 'Fa6/41', 'Gi3/40']

您可以使用new regex module

import regex

data = '''348  VLAN0348                         active    Fa4/24, Fa4/26, Gi2/4
349  VLAN0349                         active    Fa6/40, Fa6/43, Fa6/45
350  VLAN0350                         active    Fa6/41, Gi3/40'''

print regex.findall(r'(?:\G(?!^),\s*|\bactive)\s+([^\s,]+)', data)

相关问题 更多 >