There is a script that, on a regular basis, searches for values ​​in the log, but I get not only the required value, but also empty lines.
Here is an example of output, how to get only values ​​where there is text?

[('0', 'R', 'ER')] [] [] [] [] [] [('80', 'S', 'ER')] [] [('21:55:21.210', 'SEVERE', 'ER')] [] [] 

def FindError():

 patterrn1 = r'([\d\:.]+).{6}([SEVERE]+).*(ER\d{3})' regexeper = re.compile(patterrn1) print(regexeper) with open(ExistLogs) as in_file: with open(ResultFile, 'w') as out_file: for line in in_file: try: test1 = regexeper.findall(line) print(test1) except AttributeError: pass 

While I found the solution of the verification condition itself, I do not know how correct it is, but it works

 test1 = regexeper.findall(line) #print(test1) if test1 == []: pass else: print(test1) except AttributeError: pass 
  • Use if lst: instead of if lst == []: to check if there are any items in the list. - jfs
  • Regular expressions have nothing to do with it. Briefly, the question without water is: как проверить пуст ли массив в python? - ReinRaus
  • @ReinRaus Yes, most likely, the question sounds more intelligent, but why are empty lines being added, I don’t understand this, can it somehow be related to reading the file line by line? - Show

1 answer 1

The simple answer is: yes, you are reading line by line from the log file, each line is analyzed by a regular expression and the result is printed. If the regular expression did not work, it returns an empty list (it is not necessary to wrap the search in a try block: except, re.findall does not raise an exception on empty strings)

Here is an effective way to accomplish a task with generator expressions:

 import re regexeper = re.compile(r'([\d\:.]+).{6}([SEVERE]+).*(ER\d{3})') parsed_lines = (regexeper.findall(line) for line in open(ExistLogs) if regexeper.findall(line)) for parsed_line in parsed_lines: print parsed_line