我有一串像这样的经纬度的字符串
LINESTRING (-79.0578544444577 43.0929133770364, -79.0559554404751 43.0929995585932, -79.0540564364926 43.09308574015, -79.0504086322323 43.0931797561892, -79.0503228015438 43.0911427096913)
我希望将字符串中的坐标转换为数组。我知道这可以用string splitting
完成,但我不明白如何编写表达式来获取字符串中的坐标。
有人可以帮助我吗
答案 0 :(得分:4)
(
和最后一个)
", "
,您将获得包含"-79.0578544444577 43.0929133770364","-79.0559554404751 43.0929995585932",...
" "
以获取另一个String []数组,这次包含"-79.0578544444577", "43.0929133770364"
你也可以使用正则表达式来查找表格中的数字[可选-
] [一位或两位数] [点] [多于一位数]。这种模式可能看起来像"-?\\d{1,2}[.]\\d+"
答案 1 :(得分:2)
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Coordinates {
static class LatLon {
double lat;
double lon;
public LatLon( double lat, double lon ) {
this.lat = lat;
this.lon = lon;
}
@Override public String toString(){ return lat + ", " + lon; }
}
public static void main( String[] args ){
String info =
"LINESTRING (" +
"-79.0578544444577 43.0929133770364, " +
"-79.0559554404751 43.0929995585932, " +
"-79.0540564364926 43.09308574015, " +
"-79.0504086322323 43.0931797561892, " +
"-79.0503228015438 43.0911427096913)";
Pattern p = Pattern.compile( "[^\\(]+\\(([^\\)]+).*" );
Matcher m = p.matcher( info );
if( m.matches()) {
List< LatLon > coordinates = new java.util.LinkedList<>();
String[] coords = m.group( 1 ).split( "," );
for( int i = 0; i < coords.length; ++i ) {
String[] latLon = coords[i].trim().split( " " );
coordinates.add(
new LatLon(
Double.parseDouble( latLon[0] ),
Double.parseDouble( latLon[1] )));
}
System.out.println( coordinates );
}
}
}
输出:
[-79.0578544444577, 43.0929133770364, -79.0559554404751, 43.0929995585932, -79.0540564364926, 43.09308574015, -79.0504086322323, 43.0931797561892, -79.0503228015438, 43.0911427096913]
答案 2 :(得分:1)
如果您对将它们全部放在一个阵列中感到高兴:
String str = "LINESTRING (-79.0578544444577 43.0929133770364, -79.0559554404751 43.0929995585932, -79.0540564364926 43.09308574015, -79.0504086322323 43.0931797561892, -79.0503228015438 43.0911427096913)";
String[] arr = str.split("\\(|\\)")[1].split(",? ");
for (String s: arr)
System.out.println(a);
split("\\(|\\)")
表示在(
或)
上分开。那就是{"LINESTRING ", "-79...", ""}
。
[1]
因为这是包含"-79..."
的位置。
split(",? ")
表示在,
上分隔,后跟空格或空格。
如果要成对提取坐标:
for (int i = 0; i < arr.length; i += 2)
{
System.out.println("coordinate 1 = "+arr[i]);
System.out.println("coordinate 2 = "+arr[i+1]);
}
答案 3 :(得分:0)
如果LineString是变量的名称,括号内的值是什么(括号不包括),那么:
String[] coords = LINESTRING.split(" ");
应该工作!
答案 4 :(得分:0)
试试这个:
String[] coordinates = LINESTRING.split(",*\\s+");
这应该立即按空格和逗号分开。此正则表达式查找零个或多个逗号,然后查找一个或多个空格字符作为分隔符。