繁体   English   中英

如何使用正则表达式来捕获一个又一个单词,中间有换行符

[英]How to use regex to capture a word after another word, with newline in between

我一直在研究 Python 中的正则表达式,以尝试在单词出现后一次匹配某个序列。 我遇到了两个问题:1)我要搜索的文本在我想用作触发词的词和我实际想要匹配的词之间有可变数量的字符,2)文本是多线。

在以下示例文本中,我想匹配“lag-10:10”和“lag-10:20”但匹配“lag-10:30”:

    vprn 5001 name "5001" customer 1 create
        interface "to-VPLS-6663000" create
            sap lag-10:10 create
        interface "to-VPLS-3000500" create
            sap lag-10:20 create
        vpls 3410001 name "XYZBDVLAN1" customer 1 create
            sap lag-10:30 create

对于我正在使用的网络设备,“interface”和“lag”之间的文字可能会有所不同。 我最初想出的方法是只匹配序列lag-10:[^ ]*一次,并且仅在出现“interface”一词之后。 问题是......我不知道如何做到这一点。 我尝试过的所有内容都捕获了太多或没有足够的文本,并且由于“滞后”与“界面”在不同的行上这一事实而变得复杂。

任何帮助将不胜感激,因为我是 Regex 的新手!

这是在多行模式下使用re.findall的一种方法:

inp = """    vprn 5001 name "5001" customer 1 create
    interface "to-VPLS-6663000" create
        sap lag-10:10 create
    interface "to-VPLS-3000500" create
        sap lag-10:20 create
    vpls 3410001 name "XYZBDVLAN1" customer 1 create
        sap lag-10:30 create"""

matches = re.findall(r'^\s+\binterface.*?\n\s+sap (lag-\d{1,2}:\d{2})', inp, flags=re.M)
print(matches)  # ['lag-10:10', 'lag-10:20']

上面使用的正则表达式模式匹配以interface作为第一个单词的一行,然后是一行包含sap-和一个小时:分钟时间戳的行。

只要值始终如您指定的那样,这里有几个不同的解决方案应该可以工作:

import re
text = """    vprn 5001 name "5001" customer 1 create
        interface "to-VPLS-6663000" create
            sap lag-10:10 create
        interface "to-VPLS-3000500" create
            sap lag-10:20 create
        vpls 3410001 name "XYZBDVLAN1" customer 1 create
            sap lag-10:30 create"""

pattern = r'lag-\d{2}:[1-2]0'
result = re.findall(pattern,text,re.MULTILINE)
print(result)


pattern = r'lag-\d{2}:[1-2]\d{1}'
result = re.findall(pattern,text,re.MULTILINE)
print(result)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM