正则表达式校验多格式坐标:十进制纬度匹配失败排查
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
-90to90(including exact 90 with optional decimals) - Decimal longitude: Restricted to
-180to180(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
- Decimal latitude: Restricted to
- 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
相关产品推荐
相关产品推荐

