作爲輸入,我得到字符串"some text\\nsome text"
- >如"some text\nsome text"
所示。 怎麼可能刪除一個反斜槓和 "some text\nsome text"
得到 - >顯示爲用其未轉義值替換轉義轉義序列
"some text
some text"
這將也適用於其他特殊字符,如"\t"
? 隨着正則表達式有可能做只有像 textLine.replace("\\n", "\n") and so on.
有沒有另一種方式?
作爲輸入,我得到字符串"some text\\nsome text"
- >如"some text\nsome text"
所示。 怎麼可能刪除一個反斜槓和 "some text\nsome text"
得到 - >顯示爲用其未轉義值替換轉義轉義序列
"some text
some text"
這將也適用於其他特殊字符,如"\t"
? 隨着正則表達式有可能做只有像 textLine.replace("\\n", "\n") and so on.
有沒有另一種方式?
你在玩多行的正則表達式嗎? 然後你就可以編譯正則表達式:
Pattern.compile("^([0-9]+).*", Pattern.MULTILINE);
http://www.javamex.com/tutorials/regular_expressions/multiline.shtml
所以它不是那麼明顯,你想從兩個字符創建一個字符。
我做了這個方法:
String res="";
boolean backslash=false;
for(char c : "some text\\nsome text".toCharArray()){
if(c!='\\'){
if(backslash){
switch(c){
case 'n' :
res+='\n';
break;
case 't' :
res+='\t';
break;
}
backslash=false;
}else{
res+=c;
}
}
else{
backslash=true;
}
}
也許它會幫助你,它實際上只爲我把開關的情況下(EOL和選項卡)的作品。
注意:如果您想要更好的性能,請用StringBuilder替換String。
你不需要重新發明輪子。對於unescape Java字符串,您可以使用org.apache.commons.lang3.StringEscapeUtils
。 Unescape在字符串中找到任何Java文字。例如,它會將'\
'和'n
'的序列轉換爲換行符,除非'\
'前面有另一個'\
'。在這種情況下,你需要再一次使用unescape。
代碼:
import static org.apache.commons.lang3.StringEscapeUtils.unescapeJava;
public class Unescape {
public static void main(String[] args) {
System.out.println("some text\\nsome text");
System.out.println(unescapeJava("some text\\nsome text"));
}
}
輸出:
some text\nsome text
some text
some text
工程就像一個魅力。謝謝! – 2016-08-05 04:26:34
使用Apache實用程序:
StringEscapeUtils.unescapeJava(stringToUnEscape);
請不要在多個問題上發佈相同的答案。發佈一個很好的答案,然後投票/標記以重複關閉其他問題。如果問題不重複,*定製您的問題答案。* – 2016-09-20 20:46:03
's.replaceAll( 「\\\\\\\\」, 「\\\\」); – 2012-04-27 12:29:54
@MarkoTopolnik沒有做OP所要求的。 – Romain 2012-04-27 12:31:26
@Lex你不想「刪除一個反斜槓」,你想「用它的非轉義值替換一個逃逸轉義序列」。 – Romain 2012-04-27 12:32:39