10e5x
10e5x

Reputation: 909

Having problems replacing a string...to what i want

I managed to get a json response back from a request and i convert it to String lets say:

String response = client.execute(get, handler);  

The response looks something like:

"geometry":{"rings":[[[29470.26099999994,40220.076999999583],[29551.560999999754,40324.093000000343],[29597.470999999903,40391.253000000492],[29619.849999999627,40434.842000000179],[29641.708999999799,40471.713999999687],[29701.501000000164,40574.616000000387],[29722.775999999605,40611.230000000447],[29723.673000000417,40613.234999999404]]]}  

But I want to have it to look like the following one:

"Coordinates":"29470.26099999994|40220.076999999583,29551.560999999754|40324.093000000343,29597.470999999903|40391.253000000492,45360.235000003|41478.4790000003,45360.2369999997|41478.4729999993,45353.8320000004|41470.7339999992,45372.21|41468.057,45371.8090000004|41467.1390000004" 

In summary i want to change the comma between two coordinates in a [ ] set to be separated by pipes"|" instead of comma and to separate a set of two coordinates with , instead of "],["

What i tried:

response = response.replace("],[","\,");  
response = response.replace("[[[","\"");  
response = response.replace("]]]","\"");  

However it does not give me what i wanted...becuz i have no idea to achieve the replace of pipe...tot of using regex but dont know how to. can someone help me please

Upvotes: 0

Views: 84

Answers (2)

Gab
Gab

Reputation: 8323

try something like this

String result = response.replaceAll("([^\\]])(\\,)","$1\\|").replaceAll("[\\[\\]]","");

=> ([^\\]])(\\,) => ([^\])(\,) every comma not preceded by ]

=> [\\[\\]] => [\[\]] every [ or ]

Please note that

  • replacing using regexp is using String.replaceAll or Pattern class
  • String are immutable

Upvotes: 2

Dario
Dario

Reputation: 548

I think this should work:

String response = "[[[29470.26099999994,40220.076999999583],[29551.560999999754,40324.093000000343],[29597.470999999903,40391.253000000492],[29619.849999999627,40434.842000000179],[29641.708999999799,40471.713999999687],[29701.501000000164,40574.616000000387],[29722.775999999605,40611.230000000447],[29723.673000000417,40613.234999999404]]]";

response = response.replace(",", "|");
response = response.replace("]|[", ",");
response = response.replace("[[[", "\"");
response = response.replace("]]]", "\"");
System.out.println(response);

Upvotes: 0

Related Questions