开发者

Latitude/Longitude Regular Expression

I'm in the middle of developing a Twitter app. While parsing JSON I need to extract latitude and longitude, store them in a database and then later use them in an Android app. Basically, I managed to extract it, but people are sending their tweets from different devices (iPhones, Blackberries, etc.)开发者_JS百科. I'm getting different responses. Here are the examples:

ÜT: 51.554644,-0.003976
51.576100, -0.031600
Iphone: 51.554644,-0.003976

Now my question is: how can I use a regular expression to match latitude and longitude and extract it in a form of array in JavaScript regardless of the word that appears in front of it?


You could use something like this:

([0-9.-]+).+?([0-9.-]+)

Since you tagged your question with both PHP and JavaScript, I'll show you how to use it in both.

In PHP:

preg_match('/([0-9.-]+).+?([0-9.-]+)/', $str, $matches);
$lat=(float)$matches[1];
$long=(float)$matches[2];
// coords are in $lat and $long

In JavaScript:

var matches=str.match(/([0-9.-]+).+?([0-9.-]+)/);
var lat=parseFloat(matches[1]);
var long=parseFloat(matches[2]);
// coords are in lat and long

For fun, here's Python too:

import re
match = re.match(r'([0-9.-]+).+?([0-9.-]+)', str)
lat = float(match.group(1))
long = float(match.group(2))
# coords are in lat and long


This works for all strings you specified:

$str = "Iphone: 51.554644,-0.003976";

preg_match_all("/(?<lat>[-+]?([0-9]+\.[0-9]+)).*(?<long>[-+]?([0-9]+\.[0-9]+))/", $str, $matches);

$lat = $matches['lat'];
$long = $matches['long'];

var_dump($lat, $long);


i Hope this will work

UPDATE

$output= 'ÜT: 51.554644,-0.003976';
function makePerfect($x)
{ 
  return preg_replace('/[^-?0-9\.]/','', $x);
}
$lenLong=explode(',',$output);
$final=array_map('makePerfect',$lenLong);
//debug like this
echo "<pre>";
print_r($final);

display

Array
(
    [0] => 51.554644
    [1] => -0.003976
)


In javascript -

var t1 = "ÜT: 51.554644,-0.003976";
var t2 = "51.576100, -0.031600";
var t3 = "Iphone: 51.554644,-0.003976";

var reg = new RegExp(/[+-]?[\d.]+/g);

console.log(t1.match(reg));
console.log(t2.match(reg));
console.log(t3.match(reg));


format: latitude , longitude

tested with python:

(?<![0-9\.])((-?[0-8]?[0-9](\.\d*)?)|(-?90(\.[0]*)?))[\ ]*,[\ ]*((-?([1]?[0-7][0-9]|[1-9]?[0-9])(\.\d*)?)|-?180(\.[0]*)?)(?![0-9\.])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜