I am trying to display both the datetime and the IP address of my log file:
Apr 20 07:03:53 123.345.45.123
^ ^ ^ ^
|---datetime--| |-----IP-----|
my code:
datetimeRegex = re.compile(r'^\w{3}\s\d\d\s\d\d:\d\d:\d\d')
IPRegex = re.compile(r'\d+.\d+.\d+.\d{1,3}')
f = open("logfile.log","r")
count = 0
for line in f.readlines():
datetime = re.match(datetimeRegex, line)
IPaddr = re.match(IPRegex, line)
if datetime and IPaddr:
count += 1
print str(count) + ":" + str(datetime.group()) + "IP: " + str(IPaddr.group())
I tried to see what is not matching and I think it is IPaddr
that isn't matching because I removed IPaddr
from my if statment and my output would print the dates. It is when I added IPaddr
that nothing would print. So I think I am not matching my IP address correctly. However I tried a sample IP and my regex on an online regex tester and it seemed to work. Is there something missing in my REGEX? Or perhaps there is something wrong with my logic? If there is a faster or more efficient way to parse through the log file, I am open to suggestions.