Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading