如何用Java中的引号替换子字符串?

时间:2013-01-22 11:00:46

标签: java

我有一个字符串:

str="{\"type\":\"Polygon\",\"coordinates\":[[[60.677938980978993,56.834449959232998],
[60.680103564162927,56.834305549577387],[60.679971577383398,56.833005837614643],
[60.679813193248009,56.832846980836457],[60.678546120164683,56.832760331400671],
[60.678229351893869,56.831850500219574],[60.677622212708137,56.831893826015182],
[60.676830292031028,56.832139337910085],[60.67624955020122,56.832818097713471],
[60.676275947556981,56.833655699235088],[60.676328742268893,56.834724336044253],
[60.677411033860842,56.834695454369324],[60.677490225928629,56.834478841097273],
[60.677938980978993,56.834449959232998]]]}"

现在我要删除所有\

str.replaceAll("\\",""); 

得到错误:

java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
哦,我说。另一个希望删除第一个和最后一个引号:

str.substring(str.indexOf("\""),str.lastIndexOf("\""));

我得到一个字符串:

"{\"type\":\"Polygon\",\"coordinates\":[[[60.677938980978993,56.834449959232998],
[60.680103564162927,56.834305549577387],[60.679971577383398,56.833005837614643],
[60.679813193248009,56.832846980836457],[60.678546120164683,56.832760331400671],
[60.678229351893869,56.831850500219574],[60.677622212708137,56.831893826015182],
[60.676830292031028,56.832139337910085],[60.67624955020122,56.832818097713471],
[60.676275947556981,56.833655699235088],[60.676328742268893,56.834724336044253],
[60.677411033860842,56.834695454369324],[60.677490225928629,56.834478841097273],
[60.677938980978993,56.834449959232998]]]"

仅删除了最后一次}

我在这段代码片段中做错了什么?

4 个答案:

答案 0 :(得分:3)

你试过str.replaceAll("\\\\","");吗? (见https://stackoverflow.com/a/3640386/500478

答案 1 :(得分:1)

使用其中之一,

str.replaceAll("\\.", "");

 str.replaceAll("\\\\", "");

当您键入"\\"时,这实际上是一个反斜杠(由于Java字符串中的特殊字符转义)。

正则表达式也使用反斜杠作为特殊字符,您需要使用另一个反斜杠或使用DOT(.)来转义它所以最后,您需要传递"\\\\""\\."作为特殊字符。模式匹配单个反斜杠。

答案 2 :(得分:1)

       System.out.println(str.replaceAll("\\\\", ""));

输出:

  

{ “类型”: “多边形”, “坐标”:[[[60.677938980978993,56.834449959232998]   [60.680103564162927,56.834305549577387],[60.679971577383398,56.833005837614643],[60.679813193248009,56.832846980836457],[60.678546120164683,56.832760331400671],
  [60.678229351893869,56.831850500219574],[60.677622212708137,56.831893826015182],
  [60.676830292031028,56.832139337910085],[60.67624955020122,56.832818097713471],
  [60.676275947556981,56.833655699235088],[60.676328742268893,56.834724336044253]   [60.677411033860842,56.834695454369324],[60.677490225928629,56.834478841097273],[60.677938980978993,56.834449959232998]]]}

答案 3 :(得分:1)

str.replace("\\", "");

适合您的情况。

public String replace(CharSequence target,CharSequence replacement)

替代对象 此字符串的 each 子字符串与文字目标序列与指定的文字替换序列匹配。

String s = "abc" + "\\" + "def";
System.out.println(s);

它打印出以下内容 -

abc\def

\是字符串和正则表达式中的转义字符。