Regex捕获“/etc/services”

2024-10-01 17:36:22 发布

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

我想从UNIX机器上的\etc\services文件中捕获一些信息, 但是我捕捉到了错误的值,同时我认为它过于复杂了。你知道吗

我现在拥有的

with open('/etc/services') as ports_file:
    lines = ports_file.readlines()
    for line in lines:
        print re.findall('((\w*\-*\w+)+\W+(\d+)\/(tcp|udp))', line)

但它会产生这样的错误值:

[('dircproxy\t57000/tcp', 'dircproxy', '57000', 'tcp')]
[('tfido\t\t60177/tcp', 'tfido', '60177', 'tcp')]
[('fido\t\t60179/tcp', 'fido', '60179', 'tcp')]

我想要这样:

[('dircproxy', '57000', 'tcp')]
[('tfido', '60177', 'tcp')]
[('fido', '60179', 'tcp')]

我认为这个(\w*\-*\w+)+在我的正则表达式中是需要的,因为有些是这样定义的this-should-capture


Tags: 文件机器信息错误servicelineetcunix
2条回答

我建议从另一个角度来看待这个问题:与其匹配字段值,不如匹配它们之间的分隔符。你知道吗

print re.split(r'[\s/]+', line.split('#', 1)[0])[:3]

第一个line.split('#', 1)[0]删除注释(文件中第一个#之后的任何内容)。你知道吗

我个人不会在这里使用正则表达式。看看下面的解决方案,看看它是否适合您的需要(还请注意,您可以直接迭代file对象):

services = []
with open('/etc/services') as serv:
    for line in serv:
        l = line.split()
        if len(l) < 2:
            continue
        if '/tcp' in l[1] or '/udp' in l[1]:
            port, protocol = l[1].split('/')
            services.append((l[0], port, protocol))

相关问题 更多 >

    热门问题