Regex – Regular expression for matching latitude/longitude coordinates

regex

I'm trying to create a regular expression for matching latitude/longitude coordinates. For matching a double-precision number I've used (\-?\d+(\.\d+)?), and tried to combine that into a single expression:

^(\-?\d+(\.\d+)?),\w*(\-?\d+(\.\d+)?)$

I expected this to match a double, a comma, perhaps some space, and another double, but it doesn't seem to work. Specifically it only works if there's NO space, not one or more. What have I done wrong?

Best Answer

This one will strictly match latitude and longitude values that fall within the correct range:

^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$

Matches

  • +90.0, -127.554334
  • 45, 180
  • -90, -180
  • -90.000, -180.0000
  • +90, +180
  • 47.1231231, 179.99999999

Doesn't Match

  • -90., -180.
  • +90.1, -100.111
  • -91, 123.456
  • 045, 180