mel mel - 2 months ago 10
Python Question

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?

Answer

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