从不同的日志文件中匹配不同的正则表达式,并仅返回匹配项

2024-04-26 13:23:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有不同的日志文件,试图从中匹配不同的错误消息

例如,我只使用了两个日志文件,但是我有更多的日志文件,并且从每个日志文件中,我需要匹配不同的regex,因此我将在re.findall中添加越来越多的regex|

我的日志

UVM_ERROR: This is one error
UVM_ERROR: This is one error
This is my log file

new.log

No such file or directory
This is a new log file

临时工

import sys
import re
f = open(sys.argv[1] , "r").read()
op = re.findall('(UVM_ERROR.*)|(No such file or directory)', f)[0]
print op

输出

$ python temp.py my.log
('UVM_ERROR: This is one error', '')

$ python temp.py new.log
('', 'No such file or directory')

有没有办法只返回匹配的值而不返回空值

$ python temp.py my.log
'UVM_ERROR: This is one error'

$ python temp.py new.log
'No such file or directory'

我是否需要对re.findallregex用法进行任何更改以获得以上输出


Tags: or文件norelognewiserror