You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

正则表达式校验多格式坐标:十进制纬度匹配失败排查

Solution for Coordinate Validation Regex

Your original regex was failing to match decimal latitude because it only targeted individual coordinate components (not full pairs) and had an incorrect end-of-string anchor on the decimal segment. Below is a corrected regex that supports both decimal and DMS (degree/minute/second) coordinate pairs, with valid range enforcement:

^(?i)(?:
  # Decimal coordinate pair (lat, lon or lat lon)
  (?:[NS] ?)?(?:-?(?:90(?:\.0+)?|[1-8]?\d(?:\.\d+)?))(?: ?[NS])?
  (?:, ?| ?)
  (?:[EW] ?)?(?:-?(?:180(?:\.0+)?|1[0-7]\d|\d{1,2}(?:\.\d+)?))(?: ?[EW])?
|
  # DMS coordinate pair (lat then lon)
  (?:[NS] ?)?(?:90(?:° ?0+' ?0+(?:\.\d+)?")?|[1-8]?\d° ?(?:[0-5]?\d' ?(?:[0-5]?\d(?:\.\d+)?")?)?)(?: ?[NS])?
  (?: ?[EW] ?| ?)
  (?:[EW] ?)?(?:180(?:° ?0+' ?0+(?:\.\d+)?")?|(?:1[0-7]\d|\d{1,2})° ?(?:[0-5]?\d' ?(?:[0-5]?\d(?:\.\d+)?")?)?)(?: ?[EW])?
)$

Key Fixes & Features:

  • Full pair matching: Validates the entire coordinate string instead of individual components, fixing the decimal latitude issue.
  • Range enforcement:
    • Decimal latitude: Restricted to -90 to 90 (including exact 90 with optional decimals)
    • Decimal longitude: Restricted to -180 to 180 (including exact 180 with optional decimals)
    • DMS latitude: 0-90 degrees, 0-59 minutes, 0-59 seconds
    • DMS longitude: 0-180 degrees, 0-59 minutes, 0-59 seconds
  • Flexible formatting:
    • Supports optional N/S/E/W direction indicators (case-insensitive) before/after coordinates
    • Accepts comma+space or just space as separators between latitude and longitude
    • Handles optional spaces around DMS symbols (°, ', ")
  • No end-of-string anchor on partial components: Removed the incorrect $ that blocked latitude matches in comma-separated decimal pairs.

Tested Against Your Examples:

  • Decimal input: 48.20801690888307, 16.371340225941758 → matches successfully
  • DMS input: N 48° 12' 28.0044" E 16° 22' 17.1588" → matches successfully

内容的提问来源于stack exchange,提问作者Eva Zecha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 12:15:08