python3.4使用REGEX匹配字符串,然后复制以下lin

2024-04-25 19:11:24 发布

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

我已经搜索了常见问题和其他一些REGEX网站,但没有找到我的问题的答案。虽然我可以成功地执行匹配,但我无法找出最好的方法来引用匹配后的下一行以打印或添加到列表中,等等

with open("input.txt", mode='r') as sourcefile, open("output.txt", mode='w') as destinationfile:
    for codeline in sourcefile:
        if (re.match("interface GigabitEthernet0/[0123]", codeline)):
            print(codeline)

我的输入文件有以下内容。。。你知道吗

你知道吗输入.txt你知道吗

interface GigabitEthernet0/0
 Ip Address 10.10.10.10 255.255.255.0

当我执行这个时,我得到了以下的回报。。。你知道吗

interface GigabitEthernet0/0

但我想得到这个。。。你知道吗

Ip Address 10.10.10.10 255.255.255.0

在这一点上,我自己已经明白了很多,但是这个琐碎的挑战却把我绊倒了。如果迭代器的下一行与regex序列匹配,如何打印它?你知道吗

如果你能帮助我,请提前谢谢。抱歉,但这是我在Stack的第一篇文章,所以如果我没有正确格式化,我会尝试。你知道吗


Tags: 方法答案iptxt列表网站addressmode
2条回答

我能够使用next()类型来完成我的目标。你知道吗

谢谢你。你知道吗

只需设置一个标志来打印下面的行

print_next = False
for codeline in sourcefile:
    if print_next:
        print(codeline)
        print_next = False
    elif (re.match("interface GigabitEthernet0/[0123]", codeline)):
        print_next = True

相关问题 更多 >