纬度/经度正则表达式 [英] Latitude/Longitude Regular Expression

查看:79
本文介绍了纬度/经度正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Twitter应用程序。在解析JSON时,我需要提取纬度和经度,将它们存储在数据库中,然后在Android应用程序中使用它们。基本上,我设法提取它,但人们从不同的设备(iPhone,黑莓等)发送他们的推文。我得到了不同的回应。以下是示例:

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.). I'm getting different responses. Here are the examples:

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

现在我的问题是:如何使用正则表达式来匹配纬度和经度无论前面出现的单词是什么,都可以用JavaScript中的数组形式提取它?

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?

推荐答案

你可以使用像这个:

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

由于您使用PHP和JavaScript标记了您的问题,我将向您展示如何在两者中使用它。

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

在PHP中:

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

在JavaScript中:

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

为了好玩,这里也是Python:

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

这篇关于纬度/经度正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆