我有一个日志文件。我只想以“ yyyy-mm-dd”格式打印以日期开头的日志文件行,而忽略所有其他行。 日志文件如下所示: ” 流程开始
2018-01-02 This is good
2017-03-22 This is also good
What were you doing on 20-09-2016
2016-09-20 I was working
log file ends
输出应为:
2018-01-02 This is good
2017-03-22 This is also good
2016-09-20 I was working
答案 0 :(得分:1)
此正则表达式here的说明。
import re
data = """
2018-01-02 This is good
2017-03-22 This is also good
What were you doing on 20-09-2016
2016-09-20 I was working
log file ends
"""
for line in re.findall(r'^\d{4}-\d{2}-\d{2}.*$', data, flags=re.M):
print(line)
此打印:
2018-01-02 This is good
2017-03-22 This is also good
2016-09-20 I was working
答案 1 :(得分:1)
您可以使用正则表达式:
^\d{4}-\d{2}-\d{2}.*$
Python代码段:
import re
str = """
2018-01-02 This is good
2017-03-22 This is also good
What were you doing on 20-09-2016
2016-09-20 I was working
log file ends
"""
print(re.findall(r"^\d{4}-\d{2}-\d{2}.*$",str,re.MULTILINE));
输出
['2018-01-02 This is good', '2017-03-22 This is also good', '2016-09-20 I was working']
答案 2 :(得分:1)
使用re.match
例如:
import re
s = """2018-01-02 This is good
2017-03-22 This is also good
What were you doing on 20-09-2016
2016-09-20 I was working
log file ends"""
for line in s.splitlines():
if re.match(r"\d{4}-\d{2}-\d{2} ", line): #Check if each line matches condition.
print(line)
输出:
2018-01-02 This is good
2017-03-22 This is also good
2016-09-20 I was working
答案 3 :(得分:0)
使用正则表达式fullmatch
每行:
for line in lines:
m = re.fullmatch('^(\d{4}-\d{2}-\d{2}) (.*)$', line)
if m:
print(m.group())
输出:
2018-01-02 This is good
2017-03-22 This is also good
2016-09-20 I was working