簡體   English   中英

負匹配的Python正則表達式

[英]Python regex with negative matching

我有以下文本文件作為sample.txt

xe-4/3/1.1596
xe-4/3/1.1528
ae2.670
xe-4/3/1.1503
ae2
xe-4/3/1.1478
xe-4/3/1.1475
xe-4/3/1.1469
xe-4/3/1
xe-4/3/1.3465
xe-4/0/0.670
xe-4/0/0
xe-4/3/1.1446
xe-4/0/0.544
xe-4/3/1.1437
gr-5/0/0
gr-5/0/0.10
lo0.16384
lo0.16385
em1
em1.0
cbp0
demux0
irb
pip0
pp0
ae0

這是路由器的接口列表。 我需要打印出包含以下內容的行(接口): xe,ae,gr但不包含點的行(接口),例如xe-4 / 3/1gr-5 / 0/0ae2等。

嘗試以下代碼,但它不起作用:

import re

file = open('sample.txt','r')
string = file.read()

for f in string:
    matchObj = re.findall("(xe|ae|gr)[^.]*$", f)
    if matchObj:
        print f

http://regexr.com/上檢查了我的正則表達式(xe | ae | gr)[^。] * $ ,它與我想要的行匹配。 你能告訴我我在做什么錯。

for f in string:將遍歷文件中的字符; 您想遍歷行。 我建議改為以下代碼:

# use the with statement to open the file
with open('sample.txt') as file:
    for line in file:
        # use re.search to see if there is match on the line;
         # but we do not care about the actual matching strings
        if re.search("(xe|ae|gr)[^.]*$", line):
            print line

暫無
暫無

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

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