簡體   English   中英

Python 3.4-使用REGEX匹配字符串,然后復制以下行

[英]Python 3.4 - Using REGEX to Match a string and then copy the following line

我已經搜索了常見問題解答和其他一些REGEX網站,但沒有找到我的問題的答案。 雖然我可以成功執行匹配,但是我無法找出最好的方法來在匹配之后打印或添加到列表等之后引用NEXT行。這是我的圖表

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)

我的輸入文件具有以下內容...

input.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

在這一點上,我已經自己弄清楚了很多,但是這個微不足道的挑戰已經使我絆倒了。 如果它與正則表達式序列匹配,如何從迭代器向下打印下一行?

預先感謝您能為我提供幫助。 抱歉,這是我在Stack上的第一篇文章,所以如果我格式化不正確,請嘗試。

只需設置一個標志即可打印以下行

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

我能夠使用next()類型完成目標。

謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM