0

I have a log file with a consistent date in my log file.

ex:

date1

date2

...

The date means the number of logs in my log file. I was wondering how can print the dates from the log file using Regular expressions

what I have tried:

import re

dateRegex = re.compile('^\w{3}\s\d\d:\d\d:\d\d')

f = open("logfile.log","r")

for line in f.readlines():
    matches = re.findall(dateRegex,line)
    print matches

The output I am getting is (many []):

[]
[]
[]
...
...
7
  • 2
    Put an if somewhere to avoid printing when you have no matches. You might also want to print the element of the result list, as opposed to the list itself. Commented Jan 16, 2014 at 17:11
  • @nhahtdh sample datetime Apr 20 07:04:53 Commented Jan 16, 2014 at 17:12
  • 1
    You forgot to match the date. Try r'^\w{3}\s\d\d\s\d\d:\d\d:\d\d' Commented Jan 16, 2014 at 17:13
  • @Jerry no matches still =/ I was wondering is the r is needed when using re.compile? i tested it without the r for another case and it worked without it Commented Jan 16, 2014 at 17:15
  • 1
    @Jerry if you could write this as the answer I would gladly accept it thanks! Commented Jan 16, 2014 at 17:18

1 Answer 1

1

You seem to have forgotten the date:

import re

dateRegex = re.compile(r'^\w{3}\s\d\d?\s\d\d:\d\d:\d\d')
                             # ^^^^^^^ I added ? to cater for dates between 1 & 9

f = open("logfile.log","r")

for line in f.readlines():
    matches = re.findall(dateRegex,line)
    if matches:                # Check if there are matches
        print matches[0]       # Print first element of list returned by findall

I think that you can use re.match instead, since you're testing line by line and using the beginning of line anchor:

import re

dateRegex = re.compile(r'\w{3}\s\d\d?\s\d\d:\d\d:\d\d')

f = open("logfile.log","r")

for line in f.readlines():
    matches = re.match(dateRegex,line)
    if matches:
        print matches.group()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.