python动态多次出现正则表达式

2024-10-06 16:16:07 发布

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

例如,我正在尝试一个动态regex模式,它的出现情况是未知的

ip = '3.3.3.5'
stt ="""
(1.1.1.1/32, 3.3.3.5/32), abcd: xx:xx:xx, abv cd
value: eth1/1 , bbcc , time: tt:tt
text :
eth1/1 ip time << 
eth1/2 ip time <<
 """

我需要检索的是,基于获取接口所需的ip,在上面的示例中,对于3.3.3.5/32IP,我希望获取“text:”下的接口,即eth1/1和eth1/2

正则表达式我用过:

re.findall(ip+"[\/0-9,)]+\s+abcd: xx:xx:xx, abv cd\s+value: [0-9a-zA-Z\/]+ , bbcc , time: tt:tt\s+ values text\s+[0-9a-zA-Z\/]+",stt)

output : ['3.3.3.5/32), abcd: xx:xx:xx, abv cd\n value: eth1/1 , bbcc , time: tt:tt\n values text\n  eth1/1']

它返回的第一个匹配项是eth1/1,但是我不知道如何获得这两个接口,请参考


Tags: textiptimevaluecd动态eth1values
2条回答

你可以按以下步骤做:

import regex as re

string = """
(1.1.1.1/32, 3.3.3.5/32), abcd: xx:xx:xx, abv cd
value: eth1/1 , bbcc , time: tt:tt
text :
eth1/1 ip time << 
eth1/2 ip time <<

(1.1.1.1/32, 3.3.4.5/32), abcd: xx:xx:xx, abv cd
value: eth1/1 , bbcc , time: tt:tt
text :
eth1/1 ip time << 
eth1/2 ip time <<

(1.1.1.1/32, 3.3.5.5/32), abcd: xx:xx:xx, abv cd
value: eth1/1 , bbcc , time: tt:tt
text :
eth1/1 ip time << 
eth1/2 ip time <<
"""

rx = re.compile(r'''
        (?:
            \G(?!\A)
            |
            (?P<ip>\d+\.\d+\.\d+\.\d+)/32\)
        )
        (?s:
            (?:(?!^\().)*?
        )
        ^
        (?P<interface>eth\S+)
        \K
    ''', re.VERBOSE|re.MULTILINE)

result = {}; ip = None;
for match in rx.finditer(string):
    if match.group('ip'):
        ip = match.group('ip')
    try:
        result[ip].append(match.group('interface'))
    except:
        result[ip] = [match.group('interface')]

print(result)
# {'3.3.4.5': ['eth1/1', 'eth1/2'], '3.3.3.5': ['eth1/1', 'eth1/2'], '3.3.5.5': ['eth1/1', 'eth1/2']}

这将采用上面的结构(括号中的IP地址)并使用找到的第二个地址。
a demo on regex101.com。你知道吗

如果您只想在text:下输出,那么为什么不简单地:

stt.split('text:', 1)[1].strip()

相关问题 更多 >