1. 程式人生 > >java中轉義字元(回車\r\n)的替換 反轉義

java中轉義字元(回車\r\n)的替換 反轉義

原出處:http://www.51itong.net/java-string-rn-209.html

有一個的字串,列印的結果如下:

hello \r\n world

現在要把其中的 \r\n 替換為正常的回車,再次的列印即為:

hello

world

可以用

replaceAll ("\\\\r\\\\n", "\n");

因為在字元在Java中實際是這樣儲存的"hello \\r\\n world", 而  '\' 又需要轉義成 '\\'才行。

同理可得;

替換 \"  ->  "

proText = proText.replaceAll("\\\\\"", "\"");

哈哈,找到了更簡單的方法:

使用:

org.apache.commons.lang3.StringEscapeUtils

StringEscapeUtils.unescapeJava(string);