Python中使用正则表达式捕获匹配并将捕获的字符串值分配给变量

2024-06-28 20:12:01 发布

您现在位置:Python中文网/ 问答频道 /正文

刚刚开始学习python/regex。

我有一个错误日志文件,我想在其中捕获与特定模式匹配的字符串,并从中创建一个列表。每行有一个错误。我把约会时间部分记下来了。我需要提取'company'和'errorline',将它们赋给变量,追加到我的嵌套列表中。

错误行如下所示:

2013-02-02 12:20:15 blahblahblah=123214, moreblah=1021, blah.blah.blah, company=201944, errorline=#2043

f = open("/path/error.log","r")

errorlist = [["datetime","company","errorline"]]     #I want to append to nested list

for line in f:
    datetime = line[:19]
    company = re.search(r"=[0-9]{6},",line)
    company = company.group[1:-1]                    #to remove the '=' and ','
    errorline = re.search(r"#[0-9]{1,}",line)
    errorline = errorline.group()[1:]

    errorlist.append([datetime,company,errorline])

我知道这段代码不起作用,因为我无法将.group()赋给变量。

请帮忙!


Tags: 文件tore列表searchdatetime错误line