Skip to content

Instantly share code, notes, and snippets.

@babo
Last active March 2, 2019 20:03
Show Gist options
  • Save babo/f17b9ae1f024f3b9f453aaa2e918eed5 to your computer and use it in GitHub Desktop.
Save babo/f17b9ae1f024f3b9f453aaa2e918eed5 to your computer and use it in GitHub Desktop.
import re
number = r'\d+ (?: \. \d*)?' # one or more digits, followed by an optional dot and zero or more digits
coord2 = re.compile(r'\s* \( \s* (?P<lat> {number}) \s* , \s* (?P<lon> {number}) \s* \) \s*'.format(number=number), re.VERBOSE)
s = '(23.34, 11)'
match = coord2.match(s)
if match:
lat, lon = float(match.group('lat')), float(match.group('lon'))
print('Captured coordinates {:0.2f} {:0.2f}'.format(lat, lon))
# A more verbose version with comments
coord = re.compile(r"""
\s* # optional whitespace
\( # opening bracket
\s* # optional whitespace
(?P<lat> # capture latitude
\d+ # digits
(?: # optional decimal part starts, don't capture it
\. # a dot
\d* # optional decimal digits
)? # optional decimal part ends
) # end of latitude capture
\s* # optional whitespace
, # coma separating coordinates
\s* # optional whitespace
(?P<lon> # capture longitude
\d+ # digits
(?: # # optional decimal part starts, don't capture it
\. # a dot
\d* # optional decimal digits
)? # optional decimal part ends
) # end of longitude capture
\s* # optional whitespace
\) # closing bracket
\s* # optional whitespace
""", re.VERBOSE)
match = coord.match(s)
if match:
lat, lon = float(match.group('lat')), float(match.group('lon'))
print('Captured coordinates {:0.2f} {:0.2f}'.format(lat, lon))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment