regex 返回进程ID后括号中的大写消息的正则表达式

pod7payv  于 2022-11-18  发布在  其他
关注(0)|答案(7)|浏览(103)

我希望extract_pid函数在进程id之后返回带括号的大写消息。下面的代码打印pid s,但不确定如何在括号中添加大写字母:

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)

例如:

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

且输出将是:

12345 (ERROR)
bf1o4zei

bf1o4zei1#

如果在:(冒号)后面只需要大写

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

ulmd4ohb2#

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])
crcmnpdw

crcmnpdw3#

我刚刚解决了。我确实挣扎过。

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)
pn9klfpd

pn9klfpd4#

正确的正则表达式为:

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

lymgl2op5#

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]))
vwkv1x7d

vwkv1x7d6#

解决方法我发现如下:

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)

输出为:12345(错误)无无67890(正在运行)

r8xiu3jd

r8xiu3jd7#

import re
def extract_pid(log_line):
    regex = r"\[(\d+)\]\:\s\b([A-Z]*\b)" #using word boundaries makes the search case sensitive in the event our result has a mix of both lower & uppercase letters.
    result = re.search(regex, log_line)
    if result is None:
        return None
    return "{} ({})".format(result[1], result[2])

相关问题