Regular expression for matching latitude/longitude coordinates?

Viewed 167955

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?

19 Answers

@macro-ferrari I did find a way to shorten it, and without look aheads in the light of all recent talks about regex engines

const LAT_RE = /^[+-]?(([1-8]?[0-9])(\.[0-9]{1,6})?|90(\.0{1,6})?)$/;

enter image description here

const LONG_RE = /^[+-]?((([1-9]?[0-9]|1[0-7][0-9])(\.[0-9]{1,6})?)|180(\.0{1,6})?)$/;

enter image description here

Regex shorten @marco-ferrari solution by replacing the multiple use of [0-9] with subset of [0-9]. Also removed unnecessary quantifiers such as ?: from various places

lat  "^([+-])?(?:90(?:\\.0{1,6})?|((?:|[1-8])[0-9])(?:\\.[0-9]{1,6})?)$";
long "^([+-])?(?:180(?:\\.0{1,6})?|((?:|[1-9]|1[0-7])[0-9])(?:\\.[0-9]{1,6})?)$";


**Matches for Lat**

Valid between -90 to +90 with up to 6 decimals.

**Matches for Long**

Valid between -180 to +180 with up to 6 decimals.

A complete and simple method in objective C for checking correct pattern for latitude and longitude is:

 -( BOOL )textIsValidValue:(NSString*) searchedString
{
    NSRange   searchedRange = NSMakeRange(0, [searchedString length]);
    NSError  *error = nil;
    NSString *pattern = @"^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?),\\s*[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$";
    NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: pattern options:0 error:&error];
    NSTextCheckingResult *match = [regex firstMatchInString:searchedString options:0 range: searchedRange];
    return match ? YES : NO;
}

where searchedString is the input that user would enter in the respective textfield.

PHP

Here is the PHP's version (input values are: $latitude and $longitude):

$latitude_pattern  = '/\A[+-]?(?:90(?:\.0{1,18})?|\d(?(?<=9)|\d?)\.\d{1,18})\z/x';
$longitude_pattern = '/\A[+-]?(?:180(?:\.0{1,18})?|(?:1[0-7]\d|\d{1,2})\.\d{1,18})\z/x';
if (preg_match($latitude_pattern, $latitude) && preg_match($longitude_pattern, $longitude)) {
  // Valid coordinates.
}

this one enforces 3 numbers after the comma to avoid false matches:

(?<latitude>-?\d+\.\d{3,10}),(?<longitude>-?\d+\.\d{3,10})

Related