为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Java 将 GeoJSON 坐标中的纬度和经度值分别提取为所需的格式

使用 Java 将 GeoJSON 坐标中的纬度和经度值分别提取为所需的格式

四季花海 2023-10-19 21:51:18
我正在尝试将 GeoJSON 坐标拆分为单独的纬度和经度值,以达到所需的格式(如所需输出中所示)。我有一个 GeoJSON 文件,通过它我只提取坐标值。这些坐标值存储为字符串变量,如下所示 GeoJSON : ":[[[7.365046,46.948655],[7.365046,46.949254],[7.367558,46.949254],[7.367558,46.948655],[7.365046,46.948655]]]}}:如何从给定的字符串中分别提取纬度和经度的特定值。从 GeoJSON 文件中提取坐标的代码片段如下所示:String GeoJSON = GeoJSONFromFile().split("coordinates")[1];System.out.println("GeoJSON : " + GeoJSON );//Splitting within the bracketsString delims = "\\[(.*?)\\]";String[] tokens = GeoJSON.split(delims);GeoJSON = GeoJSON.split("}")[0];我想要实现的预期输出如下:\"points\": [\n" +"            {\n" +"              \"@type\": \"Point\",\n" +"              \"lat\": 46.948655,\n" +"              \"lon\": 7.365046\n" +"            },\n" +"            {\n" +"              \"@type\": \"Point\",\n" +"              \"lat\": 46.949254,\n" +"              \"lon\": 7.365046\n" +"            },\n" +"            {\n" +"              \"@type\": \"Point\",\n" +"              \"lat\": 46.949254,\n" +"              \"lon\": 7.367558\n" +"            },\n" +"            {\n" +"              \"@type\": \"Point\",\n" +"              \"lat\": 46.948655,\n" +"              \"lon\": 7.367558\n" +"            },\n" +"            {\n" +"              \"@type\": \"Point\",\n" +"              \"lat\": 46.948655,\n" +"              \"lon\": 7.365046\n" +"            }\n" "          ]最终结果应单独包含坐标,如上述格式所示。
查看完整描述

1 回答

?
侃侃尔雅

TA贡献1801条经验 获得超15个赞

我猜想类似的表达:

(?::\[\[)?\[([-+]?\d+\.\d+)\s*,\s*([-+]?\d+\.\d+)\]\s*,?(?:\]\]}})?

使用$1and $2as latand进行适当的替换lon,例如:

{\n"@type": "point",\n"lat":"$1",\n"lon":"$2"\n},\n

可能在某种程度上有效,但不完全有效。

演示

测试

import java.util.regex.Matcher;

import java.util.regex.Pattern;



public class RegularExpression{


    public static void main(String[] args){


        final String regex = "(?::\\[\\[)?\\[([-+]?\\d+\\.\\d+)\\s*,\\s*([-+]?\\d+\\.\\d+)\\]\\s*,?(?:\\]\\]\\}})?";

        final String string = ":[[[7.365046,46.948655],[7.365046,46.949254],[7.367558,46.949254],[7.367558,46.948655],[7.365046,46.948655]]]}}";

        final String subst = "{\"@type\": \"point\",\"lat\":\"$1\",\"lon\":\"$2\"},";


        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);

        final Matcher matcher = pattern.matcher(string);


        final String result = matcher.replaceAll(subst);


        System.out.println(result);


    }

}

输出

{"@type": "点","lat":"7.365046","lon":"46.948655"},{"@type": "点","lat":"7.365046","lon":" 46.949254"},{"@type": "点","lat":"7.367558","lon":"46.949254"},{"@type": "点","lat":"7.367558","经度":"46.948655"},{"@type": "点","纬度":"7.365046","经度":"46.948655"},

正则表达式电路

jex.im可视化正则表达式:

https://img1.sycdn.imooc.com/653134a00001fca718720195.jpg

查看完整回答
反对 回复 2023-10-19
  • 1 回答
  • 0 关注
  • 146 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信