[英]Get items from a string into an array with pattern
我有一串像這樣的經緯線
LINESTRING (-79.0578544444577 43.0929133770364, -79.0559554404751 43.0929995585932, -79.0540564364926 43.09308574015, -79.0504086322323 43.0931797561892, -79.0503228015438 43.0911427096913)
我想從字符串中獲取坐標到數組中。 我知道這可以通過string splitting
來完成,但是我不明白如何編寫表達式以僅從字符串中獲取坐標。
有人可以幫我嗎
(
和last )
之間的子字符串 ", "
上分割,您將得到String []數組,其中包含對,例如"-79.0578544444577 43.0929133770364","-79.0559554404751 43.0929995585932",...
" "
拆分以獲得另一個String []數組,這次包含"-79.0578544444577", "43.0929133770364"
您也可以使用正則表達式查找格式為[可選-
] [一位或兩位數字] [點] [多於一位數字]的數字。 這樣的模式可能看起來像"-?\\\\d{1,2}[.]\\\\d+"
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]
如果您很高興將它們全部放在一個陣列中:
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]);
}
如果LineString是變量的名稱,並且括號內的內容是它的值(不包括括號),則:
String[] coords = LINESTRING.split(" ");
應該管用 !
嘗試這個:
String[] coordinates = LINESTRING.split(",*\\s+");
這應該立即按空格和逗號分開。 此正則表達式查找零個或多個逗號,然后查找一個或多個空格字符作為定界符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.