Correct regex not matching anything

import re

pattern = r"/destination=(-?\d+\.\d+),(-?\d+\.\d+)/"
url = "https://www.google.com/maps/dir/?api=1&destination=12.1234567890,-12.1234567890"
result = re.search(pattern, url)
latitude = result.group(1)
longitude = result.group(2)

I expect to receive the latitude and longtitude output, but Python says AttributeError: 'NoneType' object has no attribute 'group'. I tested my regex on regex101 and it works, but I have no clue why is it not working in Python.

>Solution :

Remove the / at the beginning/end of the pattern:

import re

pattern = r"destination=(-?\d+\.\d+),(-?\d+\.\d+)"
url = "https://www.google.com/maps/dir/?api=1&destination=12.1234567890,-12.1234567890"
result = re.search(pattern, url)
latitude = result.group(1)
longitude = result.group(2)

print(latitude)
print(longitude)

Prints:

12.1234567890
-12.1234567890

Leave a Reply