[英]Latitude/Longitude Regular Expression
I'm in the middle of developing a Twitter app. 我正在开发一个Twitter应用程序。 While parsing JSON I need to extract latitude and longitude, store them in a database and then later use them in an Android app.
在解析JSON时,我需要提取纬度和经度,将它们存储在数据库中,然后在Android应用程序中使用它们。 Basically, I managed to extract it, but people are sending their tweets from different devices (iPhones, Blackberries, etc.).
基本上,我设法提取它,但人们从不同的设备(iPhone,黑莓等)发送他们的推文。 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? 现在我的问题是:如何使用正则表达式来匹配纬度和经度,并在JavaScript中以数组的形式提取它,而不管它前面出现的单词?
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. 由于您使用PHP和JavaScript标记了您的问题,我将向您展示如何在两者中使用它。
In PHP: 在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: 在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: 为了好玩,这里也是Python:
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
i Hope this will work 我希望这会奏效
$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
)
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);
In javascript - 在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: 用python测试:
(?<![0-9\.])((-?[0-8]?[0-9](\.\d*)?)|(-?90(\.[0]*)?))[\ ]*,[\ ]*((-?([1]?[0-7][0-9]|[1-9]?[0-9])(\.\d*)?)|-?180(\.[0]*)?)(?![0-9\.])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.