我的日志文件中有一个日期一致的日志文件。
例如:
date1
date2
...
日期表示我的日志文件中的日志数。我想知道如何使用正则表达式
从日志文件中打印日期我的尝试:
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
我得到的输出是(很多[]
):
[]
[]
[]
...
...
答案 0 :(得分:1)
你似乎忘记了约会:
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
我认为您可以使用re.match
代替,因为您要逐行测试并使用行锚的开头:
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()