regexcoordinatescoordinate-systems

RegEx for checking coordinates in various formats


I would like to verify a coordiantes-entry with a RegEx that will accept coordinates in the decimal format as well as in degrees/minutes/seconds.

I came as far as you can see below. It works with the degree/minutes/seconds-input but fails to identify the latitude in the decimal format, the longitude is correct:

Input e. g.:

48.20801690888307, 16.371340225941758
N 48° 12' 28.0044" E 16° 22' 17.1588"

Pattern:

(?:([0-8]?[0-9]|90)°(\s[0-5]?[0-9]')?(\s[0-5]?[0-9](,?\.?[0-9]+)?"))|((?:\w?\s?[0-9]{1,3})(?:\.?\,?[0-9]+)\s?\w?)$

I tried to find the mistake, but stranded at this point. I would be grateful for every help.


Solution

  • I'd use a less "restricted" pattern, and would code the rest, if necessary:

    \s*([NESW])\s*([0-9]+)\s*°\s*([0-9]+)\s*['\"]?\s*([0-9]+)(\.[0-9]+)?['\"]?|\s*([0-9]+)\.([0-9]{6,})\s*
    

    Code:

    import re
    
    
    def _extract(s):
        p = r"\s*([NESW])\s*([0-9]+)\s*°\s*([0-9]+)\s*['\"]?\s*([0-9]+)(\.[0-9]+)?['\"]?|\s*([0-9]+)\.([0-9]{6,})\s*"
        f = re.findall(p, s)
        return f
    
    
    s = """48.20801690888307, 16.371340225941758
    N 48° 12' 28.0044" E 16° 22' 17.1588  S   48° 12' 28.0044"  W    16°   22' 17.1588"""
    
    print(_extract(s))
    

    Prints

    [('', '', '', '', '', '48', '20801690888307'), ('', '', '', '', '', '16', '371340225941758'), ('N', '48', '12', '28', '.0044', '', ''), ('E', '16', '22', '17', '.1588', '', ''), ('S', '48', '12', '28', '.0044', '', ''), ('W', '16', '22', '17', '.1588', '', '')]
    

    Note