Search code examples
javajsonregexgeojson

Regex: select first and last occurence of [] in a String


I'm trying automate changing coordinates in a GeoJSON message:

{
    "type" : "Feature",
    "properties" : {},
    "geometry" : {
        "type" : "LineString",
        "coordinates" : [
            [
                4.399842023849487,
                51.97148460936231
            ],
            [
                4.386194944381714,
                52.003202463721045
            ]
        ]
    }
}

To do this, i'm looking for a way to select the first coordinate pair ( 4.399842023849487,51.97148460936231) and last ( 4.386194944381714,52.003202463721045. In this case, there are only 2 pairs, but regex should look for last pair.). Subsequently, these 2 selected Strings will be replaced by 2 coordinates that i've already extracted from another source.

What is the most sturdy/robust way to do this? Is regex the way to go?

EDIT:

Solved it with the org.json parser.

        JSONObject obj = new JSONObject(inputdata);
        JSONArray coordinateArr = obj.getJSONArray("coordinates");

        String firstOldCoordinate = coordinateArr.get(0).toString();
        String lastOldCoordinate = coordinateArr.get(1).toString();

        String newJSON = inputdata.replace(firstOldCoordinate, firstNewCoordinate).replace(lastOldCoordinate, lastNewCoordinate);

Solution

  • I do not consider regex as a neat and efficient solution to do all this. Instead using jQuery.parseJSON() is the best way. Check out the solution below. Here is the fiddle for that: http://jsfiddle.net/hacker1211/ewoma0tc/

        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    var obj = jQuery.parseJSON( '{"type": "Feature","properties": {},"geometry": {"type": "LineString","coordinates": [[4.399842023849487,51.97148460936231],[4.386194944381714,52.003202463721045]]}}' );
    obj.geometry.coordinates[0]=[7.399842023849487,60.97148460936231]; //your custom coordinates
    obj.geometry.coordinates[obj.geometry.coordinates.length-1]=[7.399842023849487,60.97148460936231];//your custom coordinates
    alert( obj.geometry.coordinates[0]);
    alert( obj.geometry.coordinates[obj.geometry.coordinates.length-1]);