2014-11-14 85 views
2

加雙引號簡單的辦法,我想寫的東西,返回一些search suggestion結果。在一個JSON字符串

假設我有一個這樣的字符串:

"[Harry,[harry potter,harry and david]]" 

的格式是例如[此處a_string,A_STRING_ARRAY_HERE]。

但我溫妮的輸出格式要像

[ "Harry",["harry potter","harry and david"]] 

,這樣我可以把它放到HTTP響應體。

有沒有一種簡單的方法來做到這一點,我不希望添加「」從零開始一個非常單一的字符串。

回答

3

演示

String text = "[Harry,[harry potter,harry and david]]"; 
text = text.replaceAll("[^\\[\\],]+", "\"$0\""); 

System.out.println(text); 

輸出:["Harry",["harry potter","harry and david"]]


說明:
如果我理解正確你想圍繞所有非012系列- 和 - - 和 - ]字符,用雙引號。在這種情況下可以簡單地使用replaceAll方法與正則表達式([^\\[\\],]+)其中其中

  • [^\\[\\],] - 表示一個非字符這是不[],(逗號)
  • [^\\[\\],]+ - +意味着元素之前它能夠出現一次或多次,在這種情況下,它表示不[],(逗號)一個或多個字符

現在,在更換我們可以只圍繞比賽由$0用雙括號"$0"代表group 0(整場比賽)。順便說一句,因爲"是字符串中的元字符(它用於開始和結束字符串),如果我們想創建它的字面量,我們需要將其轉義。要做到這一點,我們需要把\之前,它以它到底代表的字符串需要"$0"被寫爲"\"$0\""

更多的澄清有關組0,這$0用途(引自https://docs.oracle.com/javase/tutorial/essential/regex/groups.html):

還有一個特殊的組,組0,這總是代表整個表達式。

+0

謝謝!我會爲此測試更多,並接受你的答案,如果它適用於我所有的情況,請你解釋爲什麼'「$ 0 \」「'是這樣的,你不太明白它是什麼意思,請你更新你的答案? – Jaskey 2014-11-14 18:45:13

+0

你能更清楚地知道我答案的哪一部分不清楚嗎? 「*爲什麼」\「$ 0 \」「就像這樣*」沒有說出你不明白的東西。如果這是爲什麼每個''''之前都有'''''',那麼我在我的答案中解釋(我認爲)它。如果它是'$ 0',那麼你需要閱讀一些正則表達式教程在我的答案中),這將解釋你的組的概念,所以你會看到0組與正則表達式'(somePattern)'類似,也就是說它持有整個匹配。 – Pshemo 2014-11-14 20:44:04

0

如果格式[A_STRING,A_STRING_ARRAY_HERE]一致,只要在任何字符串中沒有逗號,那麼可以使用逗號作爲分隔符,然後相應地添加雙引號。例如:

public String format(String input) { 
    String[] d1 = input.trim().split(",", 2); 
    String[] d2 = d1[1].substring(1, d1[1].length() - 2).split(","); 
    return "[\"" + d1[0].substring(1) + "\",[\"" + StringUtils.join(d2, "\",\"") + "\"]]"; 
} 

現在,如果你調用format()以字符串"[Harry,[harry potter,harry and david]]",它會返回你想要的結果。並不是說我使用Apache Commons Lang庫中的StringUtils類將字符串數組與分隔符一起連接起來。您可以對自己的自定義功能進行相同的操作。

0

程序的這一和平的作品(你可以優化它):

//... 
String str = "[Harry,[harry potter,harry and david]]"; 

public String modifyData(String str){ 

    StringBuilder strBuilder = new StringBuilder(); 
    for (int i = 0; i < str.length(); i++) { 
     if (str.charAt(i) == '[' && str.charAt(i + 1) == '[') { 
      strBuilder.append("["); 
     } else if (str.charAt(i) == '[' && str.charAt(i + 1) != '[') { 
      strBuilder.append("[\""); 
     } else if (str.charAt(i) == ']' && str.charAt(i - 1) != ']') { 
      strBuilder.append("\"]"); 
     } else if (str.charAt(i) == ']' && str.charAt(i - 1) == ']') { 
      strBuilder.append("]"); 
     } else if (str.charAt(i) == ',' && str.charAt(i + 1) == '[') { 
      strBuilder.append("\","); 
     } else if (str.charAt(i) == ',' && str.charAt(i + 1) != '[') { 
      strBuilder.append("\",\""); 
     } else { 
      strBuilder.append(str.charAt(i)); 
     } 
    } 
return strBuilder.toString(); 
}