带负匹配的Python正则表达式

带负匹配的Python正则表达式,python,regex,Python,Regex,我有一个以下文本文件作为sample.txt: 这是路由器的接口列表。 我需要打印出包含xe、ae、gr的行(接口),但不包含dot的行(接口),例如xe-4/3/1、gr-5/0/0、ae2等 正在尝试以下代码,但不起作用: import re file = open('sample.txt','r') string = file.read() for f in string: matchObj = re.findall("(xe|ae|gr)[^.]*$", f) if

我有一个以下文本文件作为sample.txt:

这是路由器的接口列表。 我需要打印出包含xe、ae、gr的行(接口),但不包含dot的行(接口),例如xe-4/3/1、gr-5/0/0、ae2等

正在尝试以下代码,但不起作用:

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

检查了我的正则表达式(xe | ae | gr)[^.]*$,它与我想要的行匹配。你能告诉我我做错了什么吗。

对于字符串中的f:
将在文件中的字符上迭代;您想在行上迭代。我建议改为使用以下代码:

# 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

它不工作怎么办?@ForceBru很明显,“不工作”的意思是:既不产生任何输出,也不产生任何错误。@AnttiHaapala,这不工作可能意味着:给出错误,给出奇怪的输出,给出错误和奇怪的输出,什么也不给出,在不应该的时候关闭,等等,这对我来说是显而易见的,在这段代码上。Antti,谢谢你的回答。我现在明白了。如果你不介意的话,我想把我的问题扩大一点。请看编辑后的问题。“我原以为我能应付,但似乎我被卡住了。”@jeronimo777,你可以为你的扩展问题写一篇新帖子。这对我们有好处,因为它将单个问题清晰地划分为单个帖子,对您也有好处,因为您将在新问题列表中获得更多关注。
# 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