Home > Software engineering >  Search for multiple patterns using regex (and)
Search for multiple patterns using regex (and)

Time:01-28

I want to search for multiple patterns using python regex. In general I am reading data from the log file, line by line and searching for a pattern. If it matches I am extracting timestamp from that line. I have problem with first part. Right now reading is done in done in more pythonic way (I belive):

app_name = "example"
pid = 12341234
txt ="Mar 22 20:20:52.372          App1      0      Loginfo:  Application was started (example, PID: 12341234)"

if "Application was started" and pid and app_name in txt:
    print("Match found") # Prints found
else:
    print("Match not found")

It works fine but I was requested to use regex instead. I did some tries but the problem is that I am looking for specific data to be match (I do not want to match any PID in range 0-PID_MAX but a specific value):

app_name = "example"
pid = 12341234
txt ="Mar 22 20:20:52.372          App1      0      Loginfo:  Application was started (example, PID: 12341234)"

search_str = re.compile(f"/(Application was started)({app_name}),({pid})/")
if search_str.match(txt):
    print("Match found")
else:
    print("Match not found") # Prints not found

I do not know how can I use regex with AND to match all the values in that string?

CodePudding user response:

In your case you need to escape parenthesis \(...\) and denote optional whitespaces \s* in regex pattern, then apply pattern.search for a quick check for match:

txt ="Mar 22 20:20:52.372          App1      0      Loginfo:  Application was started (example, PID: 12341234)"

pat = re.compile(fr"Application was started \({app_name},\s*PID:\s*{pid}\)")
if pat.search(txt):
    print("Match found")
else:
    print("Match not found") 
  • Related