Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting unknown substring from a string in python [duplicate]

I have the following string:

HTTP/1.1 200 OK
CACHE-CONTROL: max-age=100
EXT:
LOCATION: string to be extracted followed by a \n
SERVER: FreeRTOS/6.0.5, UPnP/1.0, IpBridge/0.1
ST: urn:schemas-upnp-org:device:basic:1
USN: uuid:2f402f80-da50-11e1-9b23-0017881892ca

I want to extract whatever follows LOCATION: until the new line.

I can't do substring in string method as whatever follows 'LOCATION: ` may change.

I tried making this string into a dictionary and then retrieve the value of 'LOCATION' key. But this seems like a waste of memory and processing time. As the dictionary is useless to me apart from that value. Also the dictionary may grow geatlt in size if the string is too large

Is there any other way to extract whatever follows 'LOCATION: ` until the '\n' ??

like image 461
sukhvir Avatar asked Mar 26 '26 05:03

sukhvir


1 Answers

You extract the string using regular expressions

>>> import re
>>> string = """HTTP/1.1 200 OK
... CACHE-CONTROL: max-age=100
... EXT:
... LOCATION: http://129.94.5.95:80/description.xml
... SERVER: FreeRTOS/6.0.5, UPnP/1.0, IpBridge/0.1
... ST: urn:schemas-upnp-org:device:basic:1
... USN: uuid:2f402f80-da50-11e1-9b23-0017881892ca
... """
>>> regex = re.compile('LOCATION: (.*?)\n')
>>> m = regex.search(string)
>>> if m:
...     print m.group(1)
http://129.94.5.95:80/description.xml
like image 83
Sayan Chowdhury Avatar answered Mar 28 '26 20:03

Sayan Chowdhury