![](/img/trans.png)
[英]Python regex to remove capture email between dashes or ignore emails ending with .jpg etc
[英]Regex to capture '/etc/services'
我想從我的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
我建議從不同的角度來看這個:不是匹配字段值,而是匹配它們之間的分隔符。
print re.split(r'[\s/]+', line.split('#', 1)[0])[:3]
第一行line.split('#', 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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.