a1234
a1234

Reputation: 821

How to use regex & python to parse lat/long from a url?

I have the url: https://maps.google.com/maps?ll=44.864505,-93.44873&z=18&t=m&hl=en&gl=US&mapclient=apiv3

I wanted to extract the lat/long from the url, so that I have 44.864505,-93.44873.

So far I have (^[maps?ll=]*$|(?<=\?).*)* which gives me ll=44.864505,-93.44873&z=18&t=m&hl=en&gl=US&mapclient=apiv3 but this needs impovement. I have been trying to use pythex to work this out, but I am stuck.

Any suggestions? Thanks

Upvotes: 0

Views: 150

Answers (1)

That1Guy
That1Guy

Reputation: 7233

I wouldn't use regex, I'd use urlparse

For Python2:

import urlparse

url = 'https://maps.google.com/maps?ll=44.864505,-93.44873&z=18&t=m&hl=en&gl=US&mapclient=apiv3'
parsed = urlparse.urlparse(url)
params = urlparse.parse_qs(parsed.query)

print(params['ll'])

prints:

['44.864505,-93.44873']

For Python3 (urllib.parse) :

import urllib.parse as urlparse

url = 'https://maps.google.com/maps?ll=44.864505,-93.44873&z=18&t=m&hl=en&gl=US&mapclient=apiv3'
parsed = urlparse.urlparse(url)
params = urlparse.parse_qs(parsed.query)

print(params['ll'])

prints:

['44.864505,-93.44873']

Upvotes: 7

Related Questions