2016-02-27 116 views
0

我需要用空字符串替換給定字符串中的子字符串,並在子字符串的不同位置出現子字符串。配置單元 - 從字符串中刪除子字符串

我想刪除從字符串的這些可能的組合"fruit":"apple"和預期相應的字符串:

{"client":"web","fruit":"apple"} --> {"client":"web"} 
{"fruit":"apple","client":"web"} --> {"client":"web"} 
{"client":"web","fruit":"apple","version":"v1.0"} --> {"client":"web","version":"v1.0"} 
{"fruit":"apple"} --> null or empty string 

我用regexp_replace(str, "\,*\"fruit\"\:\"apple\"", ""),但沒有得到我預期的結果。構造正則表達式的正確方法是什麼?

+0

唯一的問題是尾隨',''後「水果」:「蘋果」'? – 2016-02-27 09:21:20

+0

解碼爲json,刪除然後重新編碼 –

回答

1

看來你正在使用JSON格式的數據。根據包含的依賴關係,您可以完全不需要正則表達式。

例如,如果您使用的是谷歌的lib GSON,那麼你就可以解析字符串到JSONObject的,然後從中

String input = "your data"; 
JsonParser parser = new JsonParser(); 
JsonObject o = parser.parse(input).getAsJsonObject(); 

try { 
    String foundValue = o.getAsJsonPrimitive("fruit").getAsString(); 
    if ("apple".equals(foundValue)) { 
     o.remove("fruit"); 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
} 
String filteredData = o.toJSONString(); 

附:除去屬性代碼不是最終版本,它可能需要處理的某些情況下(當沒有這樣的字段,或者包含非原始值),需要進一步的細節,包括它

P.P.S. IMO,使用正則表達式以這樣situatioins使得代碼的可讀性和靈活

相關問題