带负匹配的Python正则表达式

2024-04-28 17:25:10 发布

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

我有一个如下的文本文件示例.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,但不包含dot的行(接口),例如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)[^.]*$,它与我想要的行匹配。你能告诉我我做错了什么吗。你知道吗


Tags: retxt示例stringem1file文本文件xe
1条回答
网友
1楼 · 发布于 2024-04-28 17:25:10

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

相关问题 更多 >