Search code examples
javastring-parsing

Java Split String using regular expression


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?


Solution

  • 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));