仅解析第二个正则表达式匹配项(Web服务器日志)?

2024-04-19 15:54:44 发布

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

我有下面的(AWS负载平衡器格式)日志文件示例行要分析。你知道吗

http 2017-08-01T00:25:06.644602Z app/webservices/2f179337c6c8adb5
46.229.168.65:7336 172.31.26.99:82 0.000 0.574 0.000 200 200 257 192227 "GET http://trac.navit-project.org:80/timeline?from=2011-04-16T07%3A23%3A03Z&precision=second HTTP/1.1" "Mozilla/5.0 (compatible; SemrushBot/1.2~bl;
+http://www.semrush.com/bot.html)" - - arn:aws:elasticloadbalancing:us-west-2:712275310776:targetgroup/trac/34e2ac9af93f42de "Root=1-597fca61-4dfde4b02cd92cf61ace9825"

我有一个正则表达式,它至少部分工作,如下所示:

match = re.search(r'\"(?P<agent>.*?)\"', line)
print(match)

问题是正则表达式只匹配上面日志行中的第一组引号。你知道吗

<_sre.SRE_Match object; span=(138, 241), match='"GET http://trac.navit-project.org:80/timeline?fr>

有没有办法修改它以查找第二个匹配项,这样我就可以解析用户代理了?你知道吗


Tags: 文件orgprojectawswebapphttp示例
1条回答
网友
1楼 · 发布于 2024-04-19 15:54:44

将正则表达式更改为

"[^"]+"[^"]+"(?P<agent>[^"]*)"

说明:

"                     # opening first "-set
[^"]+                 # followed by anything not equal to "
"                     # closing first "
[^"]+                 # followed by anything not equal to "
"                     # opening second "-set
(?P<agent>[^"]*)      # named group agent
"                     # closing "

相关问题 更多 >