正则表达式捕获' / etc / services'

时间:2017-10-12 19:36:32

标签: python regex

我想从我的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

2 个答案:

答案 0 :(得分:1)

我建议从不同的角度来看这个:不是匹配字段值,而是匹配它们之间的分隔符。

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

第一个line.split('#', 1)[0]删除了评论(文件中第一个#之后的任何内容)。

答案 1 :(得分:0)

它个人不会在这里使用正则表达式。查看下面的解决方案并尝试查看它是否符合您的需求(还要注意您可以直接迭代文件对象):

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))