正则表达式在关键字上方两行提取日志文件的一部分

2024-09-29 21:52:56 发布

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

我正试图编写一个Python脚本来帮助解析日志文件,以便根据唯一ID搜索时间戳。文件很长,我尝试过的技巧会选择关键字行上方的所有内容。理想情况下,我希望有一个关键字(ID)和一个匹配的正则表达式附加到它的最大清晰度;我将尝试使用Python实现这一点。但是我想问一下,是否有人可以帮助我改进下面代码的正则表达式。 Regex尝试,选择\u id上方的所有内容:

((.*\n){2}).*8355371640847

以及有关守则:

 ...
    ...
    ..
    ..
    _ommited everythig: *ignore everything beyond*
    createTime: 2020-06-03T16:01:35.812Z --only this line to be selected
    employee:
      _id: 835537164084782 -- ID that is used as a reference to return 'createTime' two lines above
      code: null
      ...
      ...
      ...

Tags: 文件to代码脚本id内容技巧时间
3条回答

试试这个 (([^\n]\n[^\n]\n))*8355371640847

早上好, 我不明白,因为我肯定试过多次。但守则:

((.*\n){2}).*8355371640847

实际工作;它只选择搜索字符串上方两行的行。昨天,同一个字符串选择了所有内容,但它可能不得不做一些事情,比如我如何复制/粘贴数据库转储

多谢各位

希望你能得到这个

a = """ _ommited everythig: *ignore everything beyond*
    createTime: 2020-06-03T16:01:35.812Z  only this line to be selected
    employee:
      _id: 835537164084782   ID that is used as a reference to return 'createTime' two lines above
      code: null """
x = re.compile('([^\n]*\n[^\n]*\n)[^\n]*8355371640847')
print (x.findall(a))
x = re.compile('([^\n]*\n)[^\n]*\n[^\n]*8355371640847')
print (x.findall(a))

输出为: ['createTime:2020-06-03T16:01:35.812Z仅选择此行\n员工:\n'] ['createTime:2020-06-03T16:01:35.812Z仅选择此行\n']

相关问题 更多 >

    热门问题