简体   繁体   中英

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. 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...

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

Replace double quotes as below from last IP Adress.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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