的test.txt:
this is the http ip : 1.1.1.1:678 blah blah.com2
this is the https ip : 1.1.1.2:654 blah blah.com2
this is the http ip : 1.1.1.4:456 blah blah.com2
the sever this is the http ip : 1.1.1.4:456 blah blah.com2
从上面的文本文件中,我只想grep IP地址:以“http ip”开头的端口号,如下所示。
应该打印:
1.1.1.1:678
1.1.1.4:456
我尝试过以下python代码:
import re
file_open = open("test.txt", 'r')
for i in file_open:
if re.findall(".*http(.*)",i):
print i[0]
如果我运行上面的python代码,它会打印:
2
2
2
有什么想法解决这个问题吗?
答案 0 :(得分:2)
试试这个:
import re
file_open = open("test.txt", 'r')
for i in file_open:
result = re.match('.*(http ip : )([0-9:.]+)', i)
if result:
print result.group(2)
对于包含这些内容的test.txt
this is the http ip : 1.1.1.1:678 blah blah.com2
this is the https ip : 1.1.1.2:654 blah blah.com2
this is the http ip : 1.1.1.4:456 blah blah.com2
the sever this is the http ip : 1.1.1.4:456 blah blah.com2
这是输出:
1.1.1.1:678
1.1.1.4:456
1.1.1.4:456