有问题替换字符串...到我想要的

时间:2014-04-01 07:44:21

标签: java string replace

我设法从请求中获取json响应,然后将其转换为String,让我们说:

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

响应类似于:

"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]]]}  

但我想让它看起来像下面那样:

"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" 

总之,我想改变[]集中两个坐标之间的逗号,用管道分隔" |"而不是逗号并用一个两个坐标分隔,而不是"],["

我尝试了什么:

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

然而它并没有给我我想要的东西... becuz我不​​知道如何使用正则表达式替换管道...但不知道如何。请有人帮帮我

2 个答案:

答案 0 :(得分:2)

尝试这样的事情

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

=> ([^ \\]])(\\,)=> ([^\])(\,)每个逗号前面都没有]

=> [\\ [\\]] => [\[\]]每[或]

请注意

  • 使用regexp替换正在使用String.replaceAll或Pattern class
  • 字符串是不可变的

答案 1 :(得分:0)

我认为这应该有效:

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