我正在尋找內置的Java函數,例如可以將"\\n"
轉換爲"\n"
。是否有解析轉義字符的Java函數?
事情是這樣的:
assert parseFunc("\\n") = "\n"
還是我必須手動搜索和替換所有的轉義字符?
我正在尋找內置的Java函數,例如可以將"\\n"
轉換爲"\n"
。是否有解析轉義字符的Java函數?
事情是這樣的:
assert parseFunc("\\n") = "\n"
還是我必須手動搜索和替換所有的轉義字符?
您可以從Apache Commons Lang使用StringEscapeUtils.unescapeJava(s)
。它適用於所有轉義序列,包括Unicode字符(即\u1234
)。
這就是我一直在尋找的! unicode遇到了php的json_encode中的字符 – Tschallacka 2016-05-26 16:34:51
只使用字符串自己的replaceAll方法。
result = myString.replaceAll("\\n", "\n");
但是,如果你想匹配所有轉義序列,那麼你可以使用一個匹配器。有關使用Matcher的非常基本的示例,請參閱http://www.regular-expressions.info/java.html。
Pattern p = Pattern.compile("\\(.)");
Matcher m = p.matcher("This is tab \\t and \\n this is on a new line");
StringBuffer sb = new StringBuffer();
while (m.find()) {
String s = m.group(1);
if (s == "n") {s = "\n"; }
else if (s == "t") {s = "\t"; }
m.appendReplacement(sb, s);
}
m.appendTail(sb);
System.out.println(sb.toString());
您只需要根據要處理的轉義數量和類型將作業更復雜一些。 (警告:這是空氣的代碼,我不是Java開發人員)
如果我爲每個易犯字符都進行replaceAll,即8次,那麼這不會是一個性能問題嗎? (http://java.sun.com/docs/books/tutorial/java/data/characters.html) – 2009-08-25 11:26:11
對不起,我只是展示了一個簡單的案例(它是我們許多人做的事情中的一個詭計)真的不能回答你的問題)。這就是爲什麼我指出你在Matcher類,它與一個StringBuffer結合,你可以在一個通道中創建一個結果字符串。 – AnthonyWJones 2009-08-25 11:34:57
安東尼是99%正確的 - 因爲反斜線也是正則表達式保留字符,它需要被轉義兩次:
result = myString.replaceAll("\\\\n", "\n");
如果你不想列出所有可能的轉義字符,你可以委託這屬性行爲
String escapedText="This is tab \\t and \\rthis is on a new line";
Properties prop = new Properties();
prop.load(new StringReader("x=" + escapedText + "\n"));
String decoded = prop.getProperty("x");
System.out.println(decoded);
這種處理所有可能的字符
你的意思是要替換\\ n換行符? – AnthonyWJones 2009-08-25 10:27:30