mel mel - 3 months ago 12
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?


Just split the string and get last two elements.

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

If first IP Adress is required...

>>> tmp_list[0]

Replace double quotes as below from last IP Adress.

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