什么正则表达式将检查 GPS 值?
我让用户通过表单输入 GPS 值,它们都有相同的表单,一些示例:
49.082243,19.302628
48.234142,19.200423
49.002524,19.312578
我想使用 PHP 检查输入的值(我猜使用 preg_match()
),但作为我不擅长正则表达式(哦,愚蠢的我,我终于应该学习它,我知道),我不知道如何编写表达式。
显然应该是:
2x(数字)、1x(点)、6x(数字)、1x(逗号)、2x(数字)、1x(点)、6x(数字)
有什么建议如何在正则表达式中编写这个?
I'm letting users enter GPS values through a form, they all have the same form, some examples:
49.082243,19.302628
48.234142,19.200423
49.002524,19.312578
I want to check the entered value using PHP (using preg_match()
, I guess), but as I'm not good in regex expressions (oh, dumb me, I should finally learn it, I know), I don't know how to write the expression.
Obviously it should be:
2x (numbers), 1x (dot), 6x (numbers), 1x (comma), 2x (numbers), 1x (dot), 6x (numbers)
Any suggestions how to write this in regex?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我看到的其他答案没有考虑到经度从 -180 到 180,纬度从 -90 到 90。
正确的正则表达式是(假设顺序是“纬度,经度”):
这个正则表达式涵盖纬度不小于-90且不大于90,经度不小于-180且不大于180,同时允许输入整数和任意数字小数位数从 1 到 6,如果您想允许更高的精度,只需将 {1,6} 更改为 {1,x},其中 x 是小数位数
此外,如果您在组 1 上捕获,您将获得纬度和 a第 2 组的捕获获取经度。
The other answers I see don't take into account that longitude goes from -180 to 180 and latitude goes from -90 to 90.
The proper regex for this would be (assuming the order is "latitude, longitude"):
This regex covers having no less than -90 and no more than 90 for latitude as well as no less than -180 and no more than 180 for longitude while allowing them to put in whole numbers as well as any number of decimal places from 1 to 6, if you want to allow greater precision just change {1,6} to {1,x} where x is the number of decimal place
Also, if you capture on group 1 you get the latitude and a capture on group 2 gets the longitude.
类似于:
^
锚点位于输入-?
的开头,允许但不要求使用负号\d{1,2}
需要 1 或 2 个十进制数字\.
需要一个小数点\d{6}
需要正好 6 个十进制数字,
匹配单个逗号$
锚点我包含了捕获括号,以便您提取各个坐标。如果您不需要,请随意忽略它们。
全面有用的正则表达式参考:http://www.regular-expressions.info/reference.html< /a>
Something like:
^
anchors at the start of input-?
allows for, but does not require, a negative sign\d{1,2}
requires 1 or 2 decimal digits\.
requires a decimal point\d{6}
requires exactly 6 decimal digits,
matches a single comma$
anchors at the end of inputI have included capturing parentheses to allow you to extract the individual coordinates. Feel free to omit them if you don't need that.
All-around useful regex reference: http://www.regular-expressions.info/reference.html
扩展另一个答案:
Expanding on the other answer:
根据您的示例,这将完成:
说明:
Based on your example, this will do it:
Explanation: