【发布时间】:2018-11-28 17:10:23
【问题描述】:
我正在尝试使用 Python Regex 从日志的最后一行获取 IP 地址。
如果我搜索整个日志,我可以获得一个 IP。例如:
with open("read.log", "r+") as log:
for line in log:
address = "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$"
match = re.match(address, line)
但是当我尝试只读取最后一行并获取 IP 地址时,我没有得到任何结果。我该如何解决这个问题?
import re
def run():
try:
logfile = open('read.log', 'r')
# print ('First line in log: ',logfile.readline())
for line in logfile:
x = line
for ip in x:
address = "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$"
match = re.match(address, ip)
logfile.close
print ('Last Line: ', match)
except OSError as e:
print (e)
run()
我的 read.log 看起来像这样...
10.1.177.198 Tue Jun 19 09:25:16 CDT 2018
10.1.160.198 Tue Jun 19 09:25:38 CDT 2018
10.1.177.198 Tue Jun 19 09:25:36 CDT 2018
10.1.177.198 Tue Jun 19 09:26:38 CDT 2018
10.1.177.198 Tue Jun 19 09:27:16 CDT 2018
10.1.177.198 Tue Jun 19 09:28:38 CDT 2018
【问题讨论】:
-
您关闭
logfile太早了? (在 for 循环中) -
for ip in x正在遍历该行的字符。 -
也许你打算使用
x = line.split()? -
@Barmar Iterate in characters of lines 对你来说不是必须的,
re.match已经为你做了。 -
IP总是第一个字段吗?只需使用
ip = line.split()[0]
标签: python regex python-3.5