在python中使用正则表达式模式匹配时获取第一个单词

时间:2018-02-28 20:28:05

标签: python regex

输入如下所示,我希望输出成为第一个接口,其中status = [up]:在这个例子中,输出应该是Ethernet1 / 48

Last bundled member is Ethernet1/48
Ports:   Ethernet1/45    [active ] [down]
         Ethernet1/46    [active ] [down]
         Ethernet1/47    [active ] [down] *
         Ethernet1/48    [active ] [up]
         Ethernet2/1/1   [active ] [up]
         Ethernet2/1/2   [active ] [up]
         Ethernet2/1/3   [active ] [up]
         Ethernet2/1/4   [active ] [up]

3 个答案:

答案 0 :(得分:2)

我想我明白了,这段代码很有用:

import re

text = """
Last bundled member is Ethernet1/48
Ports:   Ethernet1/45    [active ] [down]
         Ethernet1/46    [active ] [up]
         Ethernet1/47    [active ] [up] *
         Ethernet1/48    [active ] [up]
         Ethernet2/1/1   [active ] [up]
         Ethernet2/1/2   [active ] [up]
         Ethernet2/1/3   [active ] [up]
         Ethernet2/1/4   [active ] [up]
"""


pattern = '\w+\S+(?=\s*\[\w+ \] \[up\])'
result = re.findall(pattern, text, re.MULTILINE)
print result[0].strip()

我编辑了模式以匹配其他可能的输出,例如: 如果[up]是第一行,那么旧的模式也会匹配端口:word 如果使用的协议不是LACP,则输出将[on] [up]而不是[active] [up]。

由于

答案 1 :(得分:1)

您可以使用

import re

string = """
Last bundled member is Ethernet1/48
Ports:   Ethernet1/45    [active ] [down]
         Ethernet1/46    [active ] [down]
         Ethernet1/47    [active ] [down] *
         Ethernet1/48    [active ] [up]
         Ethernet2/1/1   [active ] [up]
         Ethernet2/1/2   [active ] [up]
         Ethernet2/1/3   [active ] [up]
         Ethernet2/1/4   [active ] [up]
"""

rx = re.compile(r'Ethernet\S+(?=\s*\[active \] \[up\])')
match = rx.search(string)
if match:
    print(match.group(0))

哪个收益

Ethernet1/48

答案 2 :(得分:0)

这有效

<强> CODE

test_str = '''
    Last bundled member is Ethernet1/48\n
    Ports:   Ethernet1/45    [active ] [down]\n
             Ethernet1/46    [active ] [down]\n
             Ethernet1/47    [active ] [down] *\n
             Ethernet1/48    [active ] [up]\n
             Ethernet2/1/1   [active ] [up]\n
             Ethernet2/1/2   [active ] [up]\n
             Ethernet2/1/3   [active ] [up]\n
             Ethernet2/1/4   [active ] [up]
             '''

for line in test_str.split('\n'):
    if '[up]' in line:
        tmp_line = line.split(' ')

        flag = False

        for word in tmp_line:
            if word:
                print(word)
                flag=True
                break

        if flag:
            break

<强>输出

Ethernet1/48