I am new to python.I have below text lines from a text file:
05/01/2023 05:39:35 Exit with status 0 but no images found
05/01/2023 05:39:35 server12349 is considered prod. Total environments: "production"
05/01/2023 05:39:35 Platform is wnv and datatype is os
05/01/2023 05:39:35 Alertdatatype os is Windows OS
05/01/2023 05:39:35 Windows OS backup of server12349 (srv.lab.ch.os.wnv.server12349.xyz) succeeded
-
05/01/2023 05:39:35 Exit with status 0 but no images found
05/01/2023 05:39:35 server7329 is considered prod. Total environments: "production"
05/01/2023 05:39:35 Platform is wnv and datatype is os
05/01/2023 05:39:35 Alertdatatype os is Windows OS
05/01/2023 05:39:35 Windows OS backup of server7329 (srv.lab.ch.os.wnv.server7329.xyz) succeeded
I waned to capture below using regex function:
Exit with status 0 but no images found
backup of server12349 (srv.lab.ch.os.wnv.server12349.xyz)
Below pattern matches Exit with status 0 but no images found (or) backup of server12349 (srv.lab.ch.os.wnv.server12349.xyz) but I wanted have pattern to search for both in the text file. Any help would be much appreciated.
import re
pattern =re.compile(r'(Exit(.*)\sfound) |backup of\s(\w+)\s\((.*?)\)',re.MULTILINE)
with open('c:\\tmp\\Notext.txt', 'r') as myfile:
for i in myfile:
if pattern.search(i) != None:
res=re.findall(pattern,i)
#print(res)
st=list(res[0])
print(st[0],st[1])
Assuming you want to print the entire line from the file that contains either of the patterns then:
import re
pattern = re.compile(r'(^.*Exit.*found$)|(^.*backup of \w+ \(.*\).*$)')
with open('c:\\tmp\\Notext.txt') as txt:
for line in map(str.strip, txt):
for m in pattern.findall(line):
for t in m:
if t:
print(t)
Output:
05/01/2023 05:39:35 Exit with status 0 but no images found
05/01/2023 05:39:35 Windows OS backup of server12349 (srv.lab.ch.os.wnv.server12349.xyz) succeeded
05/01/2023 05:39:35 Exit with status 0 but no images found
05/01/2023 05:39:35 Windows OS backup of server7329 (srv.lab.ch.os.wnv.server7329.xyz) succeeded