2014-11-14 232 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(); 
}