gpt4 book ai didi

python - 为什么 "\n"字符出现在匹配的正则表达式模式结果中?

转载 作者:太空宇宙 更新时间:2023-11-03 20:39:39 24 4
gpt4 key购买 nike

我正在尝试解析日志文件并提取某些捕获组,例如时间戳、用户名等。当我执行以下代码时,结果是一个列表元素,其中嵌套了元组作为捕获组(或搜索结果)。基本上,我很好奇为什么我的捕获组之一中会出现 '\n' 字符,我不希望出现这种情况。

我尝试修改正则表达式模式,但无法解决问题。

import re

with open('obis1-query.log') as myfile:
StartTime = []
myfile = myfile.read()
mysearch = re.findall('(?P<datetime>\d+-\d+-\d+T\d+:\d+:\d+.\d+-05:00).\s.\w+.\s.\w+:\d.\s.+ecid:\s[A-Za-z\d,:-]+.\s.sik:\s\w+.\s.tid:\s\w+.\s.messageid:\s\w+-\d+.\s.requestid:\s\w+.\s.(?P<sessionid>sessionid:\s\w+).\s.(?P<username>username:\s\w+).\s#+\s\[\[\s-+\sSQL\sRequest,\s(?P<logreqhash>logical\srequest\shash:\n?\w+)', myfile)

if mysearch != None:
StartTime.append(mysearch)
print(StartTime)

输出如下:

[[('2019-06-12T09:14:54.947-05:00', 'sessionid: bf710000', 'username: 
kadaniel', 'logical request hash:\n83bf7e6f'), ('2019-06-12T09:14:55.343-
05:00', 'sessionid: bf710000', 'username: kadaniel', 'logical request
hash:\n8e45939b'), ('2019-06-12T09:14:55.362-05:00', 'sessionid:
bf710000', 'username: kadaniel', 'logical request hash:\n4496de01'),

我只想从结果中删除“逻辑请求哈希:”和“以下数字”(在最后一种情况下为 4496de01)之间的“\n”字符。

最佳答案

考虑使用 .replace("\n", "") 删除 \n 字符

关于python - 为什么 "\n"字符出现在匹配的正则表达式模式结果中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56937915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com