[英]How to replace any of the substrings in a string with empty substring “” (remove substring) in java
[英]How to replace substring with quotes in 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]]]"
僅最后一個}
被刪除。
我在這段代碼片段中做錯了什么?
您是否嘗試過str.replaceAll("\\\\\\\\","");
? (請參閱https://stackoverflow.com/a/3640386/500478 )
使用其中之一,
str.replaceAll("\\.", "");
要么
str.replaceAll("\\\\", "");
當您鍵入"\\\\"
,實際上是一個反斜杠(由於轉義了Java字符串中的特殊字符)。
正則表達式還使用反斜杠作為特殊字符,因此您需要使用另一個反斜杠或使用DOT(.)
對其進行轉義DOT(.)
因此,最后,您需要傳遞"\\\\\\\\"
或"\\\\."
作為匹配單個反斜杠的模式。
System.out.println(str.replaceAll("\\\\", ""));
輸出:
{“ type”:“ Polygon”,“ coordinates”:[[[[60.677938980978993,56.834449959232998],[60.680103564162927,56.834305549577387],[60.679971577383398,56.833005837614643],[60.679813193248009,56.832846980836457],[60.678546120
[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.replace("\\", "");
適用於您的情況。
public String replace(CharSequence target,CharSequence replacement)
用指定的文字替換序列替換此字符串中與文字目標序列匹配的每個子字符串。
String s = "abc" + "\\" + "def";
System.out.println(s);
它打印出以下內容-
abc\def
\\是字符串和正則表達式中的轉義字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.