简体   繁体   English

正则表达式是从日志中提取数据的最佳方法吗

[英]Is regex the best way to extract data from log

I've got a file full of log and I'm trying to extract some data from those log, a log look like: 我有一个充满日志的文件,我正试图从那些日志中提取一些数据,日志看起来像:

IP_adress - - [Date_time] "method" response_nb time "page" "UA" "IP_adress"

I want to extract the IP_adress and UA. 我想提取IP_adress和UA。 Is using a regex a good idea to extract data from those log or is there some other way to do it properly? 使用正则表达式是从这些日志中提取数据的好主意还是有其他适当的方法?

Just split the string and get last two elements. 只需拆分字符串并获取最后两个元素。

>>>
>>> str = 'IP_adress - - [Date_time] "method" response_nb time "page" "UA" "IP_a
dress"'
>>> tmp_list = str.split()
>>>
>>> tmp_list
['IP_adress', '-', '-', '[Date_time]', '"method"', 'response_nb', 'time', '"page
"', '"UA"', '"IP_adress"']
>>> tmp_list[-1]
'"IP_adress"'
>>> tmp_list[-2]
'"UA"'
>>>

If first IP Adress is required... 如果需要第一个IP地址...

>>> tmp_list[0]
'IP_adress'
>>>

Replace double quotes as below from last IP Adress. 在上一个IP地址中,如下替换双引号。

>>>
>>> tmp_list[-1].replace('"','')
'IP_adress'
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM