使用Java将GeoJSON坐标中的Lat和Long值分别提取为所需格式
我正在尝试将GeoJSON坐标拆分为不同的纬度和经度值,并转换为所需的格式(如所需输出中所示) 我有一个GeoJSON文件,通过它我只提取坐标值。这些坐标值存储为字符串变量,如图所示:使用Java将GeoJSON坐标中的Lat和Long值分别提取为所需格式,java,regex,geojson,Java,Regex,Geojson,我正在尝试将GeoJSON坐标拆分为不同的纬度和经度值,并转换为所需的格式(如所需输出中所示) 我有一个GeoJSON文件,通过它我只提取坐标值。这些坐标值存储为字符串变量,如图所示: GeoJSON::[[7.365046,46.948655],[7.365046,46.949254],[7.367558,46.949254],[7.367558,46.948655],[7.365046,46.948655]}。 如何从给定字符串中分别提取纬度和经度的特定值。从GeoJSON文件提取坐标的代码
GeoJSON::[[7.365046,46.948655],[7.365046,46.949254],[7.367558,46.949254],[7.367558,46.948655],[7.365046,46.948655]}
。
如何从给定字符串中分别提取纬度和经度的特定值。从GeoJSON文件提取坐标的代码段如下所示:
字符串GeoJSON=GeoJSONFromFile().split(“坐标”)[1];
System.out.println(“GeoJSON:+GeoJSON”);
//括号内的拆分
字符串delims=“\\[(.*?\\]”;
String[]tokens=GeoJSON.split(delims);
GeoJSON=GeoJSON.split(“}”)[0];
我希望达到的预期产出如下:
“点”:[\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”
" ]
最终结果应分别包含上述格式所示的坐标。我猜表达式类似于:
(?::\[\[)?\[([-+]?\d+\.\d+)\s*,\s*([-+]?\d+\.\d+)\]\s*,?(?:\]\]}})?
使用$1
和$2
作为lat
和lon
的适当替换,例如:
{\n"@type": "point",\n"lat":"$1",\n"lon":"$2"\n},\n
可能在某种程度上有效,但并不完全有效
试验
输出
{“@type”:“point”,“lat”:“7.365046”,“lon”:“46.948655”},{“@type”:
“点”,“纬度”:“7.365046”,“长”:“46.949254”},{“@type”:
“点”,“纬度”:“7.367558”,“长”:“46.949254”},{“@type”:
“点”,“纬度”:“7.367558”,“长”:“46.948655”},{“@type”:
“点”,“纬度”:“7.365046”,“经度”:“46.948655”}
正则表达式电路
可视化正则表达式:
RegEx电路和演示对于可视化和理解我的问题非常有用。@Emma现在我对RegEx更感兴趣,谢谢你的详细解释。
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);
}
}