Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract two double Values from String using RegEx in Java

Tags:

java

regex

I am reading a file by line and need to extract latitude and longitude from it. This how lines can looks:

DE  83543   Rott am Inn Bayern  BY  Oberbayern      Landkreis Rosenheim 47.983  12.1278 
DE  21147   Hamburg Hamburg HH          Kreisfreie Stadt Hamburg    53.55   10  

What's for sure is, there are no dots surrounded by digits except for the ones representing the doubles. Unfortunately there are Values without a dot, so it's probably best to check for numbers from the end of the String.

thanks for your help!

like image 423
tzippy Avatar asked May 31 '10 13:05

tzippy


2 Answers

If you can use the java.lang.String#split()

//Split by tab
String values[] = myTextLineByLine.split("\t");
List<String> list = Arrays.asList(values);
//Reverse the list so that longitude and latitude are the first two elements
Collections.reverse(list);

String longitude = list.get(0);
String latitude = list.get(1);
like image 73
Shervin Asgari Avatar answered Sep 30 '22 15:09

Shervin Asgari


Is it a tabulator separated csv table? Then I'd suggest looking at String#split and simply choosing the two last fields from the resulting String array.

... anyway, even if not csv, split on whitechars and take the two last fields of the String array - those are the lat/lon values and you can convert them with Double#parseDouble.

like image 40
Andreas Dolk Avatar answered Sep 30 '22 15:09

Andreas Dolk