'regular expression to return the uppercase message in parenthesis, after the process id

I want the extract_pid function to return the uppercase message in parenthesis, after the process id. Following code is printing pids but not sure how to add capital letters in parenthesis:

def extract_pid(log_line):
  regex = r"\[(\d+)\]+[A-Z]"
  result = re.search(regex, log_line)
  if result is None:
    return None
  return "{} ({})".format(result[1], result)

For example:

print(extract_pid("July 31 07:51:48 mycomputer bad_process[12345]: ERROR Performing package upgrade"))

and output would be:

12345 (ERROR)


Solution 1:[1]

 import re def extract_pid(log_line):
     regex = r"\[(\d+)\]\: ([A-Z]*)"
     result = re.search(regex, log_line)
     if result is None:
         return None
     return "{} ({})".format(result[1],result[2])

Solution 2:[2]

If we want only upper case after :(colon)

regex = r"\[(\d+)\]\: ([A-Z]+)"

Solution 3:[3]

I just solved. I did struggle though.

import re
def extract_pid(log_line):
    regex = r"\[(\d+)\]\: (\w+)"
    result = re.search(regex, log_line)
    if result is None:
        return None
    return "{} ({})".format(result[1], result[2])

print(extract_pid("July 31 07:51:48 mycomputer bad_process[12345]: ERROR Performing package upgrade")) # 12345 (ERROR)
print(extract_pid("99 elephants in a [cage]")) # None
print(extract_pid("A string that also has numbers [34567] but no uppercase message")) # None
print(extract_pid("July 31 08:08:08 mycomputer new_process[67890]: RUNNING Performing backup")) # 67890 (RUNNING)

Solution 4:[4]

The correct Regex expression is :

r"\[(\d+)\]\: ([A-Z]+)"

Solution 5:[5]

import re
def extract_pid(log_line):
    regex = r"\[(\d+)\]:\s\b([A-Z]*)\b"
    result = re.search(regex, log_line)
    if result is None:
        return None
    return "{} ({})".format(result[1], (result[2]))

Solution 6:[6]

Solution I found as follows:

import re
def extract_pid(log_line):
regex = r"\[(\d+)\]:\s([A-Z]*)\s"
result = re.search(regex, log_line)
if result is None:
    return None
return "{} ({}) ".format(result[1],result[2])

print(extract_pid("July 31 07:51:48 mycomputer bad_process[12345]: ERROR 
Performing package upgrade")) # 12345 (ERROR)
print(extract_pid("99 elephants in a [cage]")) # None
print(extract_pid("A string that also has numbers [34567] but no uppercase 
message")) # None
print(extract_pid("July 31 08:08:08 mycomputer new_process[67890]: RUNNING 
Performing backup")) # 67890 (RUNNING)

And The output is : 12345 (ERROR) None None 67890 (RUNNING)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nino_701
Solution 2 kunal20
Solution 3 David Buck
Solution 4 Reza Rahemtola
Solution 5 Syscall
Solution 6 Mandar Gite