2

I have string that reads ParseGeoPoint[30.132531,31.312511]. How can I get the coordinates saved in double variables. i.e. I want to have double lat = 30.132531; and double lang = 31.312511;

Here is what I have tried:

String myText = "ParseGeoPoint[30.132531,31.312511]";
String [] latlong= myText.split("["); //it needs an escape character
String [] latlong2= latlong[1].split(",");
Double lat = Double.parseDouble(latlong2[0]);
String[] latlong3= latlong2[1].split("]");//also an escape character is needed here
Double lang = Double.parseDouble(latlong3[0]);

Two things: How to split on the square bracket given that it needs an escape character? Second, I feel it is too much to do it in this way. There must be simpler way. What is it?

1 Answer 1

2

How to split on the square bracket given that it needs an escape character?

I guess you mean that this doesn't compile:

String [] latlong= myText.split("[");

To make it compile, escape the [:

String [] latlong= myText.split("\\[");

Here's another way to extract the doubles from the string using regular expressions:

Pattern pattern = Pattern.compile("ParseGeoPoint\\[([\\d.-]+),([\\d.-]+)]");
Matcher matcher = pattern.matcher(myText);
if (matcher.matches()) {
    lat = Double.parseDouble(matcher.group(1));
    lang = Double.parseDouble(matcher.group(2));
}

Another way is using substrings:

int bracketStartIndex = myText.indexOf('[');
int commaIndex = myText.indexOf(',');
int bracketEndIndex = myText.indexOf(']');
lat = Double.parseDouble(myText.substring(bracketStartIndex + 1, commaIndex));
lang = Double.parseDouble(myText.substring(commaIndex + 1, bracketEndIndex));
Sign up to request clarification or add additional context in comments.

2 Comments

would you explain the regular expression you used in the first answer?
The two ([\\d.-]+) are the most important. These are called capture groups, the inside of the (...) can be extracted using matcher.group(index) calls. There I match 1 or more digits or dot or minus sign. It's not very strict, for example ---... would match too, even though it's complete non-sense. But I hope you get the idea. The expression could be improved to make it more strict and robust. The rest of the expression outside the capture groups is fixed strings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.