2009-08-25 98 views

回答

1

只使用字符串自己的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開發人員)

+0

如果我爲每個易犯字符都進行replaceAll,即8次,那麼這不會是一個性能問題嗎? (http://java.sun.com/docs/books/tutorial/java/data/characters.html) – 2009-08-25 11:26:11

+0

對不起,我只是展示了一個簡單的案例(它是我們許多人做的事情中的一個詭計)真的不能回答你的問題)。這就是爲什麼我指出你在Matcher類,它與一個StringBuffer結合,你可以在一個通道中創建一個結果字符串。 – AnthonyWJones 2009-08-25 11:34:57

3

安東尼是99%正確的 - 因爲反斜線也是正則表達式保留字符,它需要被轉義兩次:

result = myString.replaceAll("\\\\n", "\n"); 
0

如果你不想列出所有可能的轉義字符,你可以委託這屬性行爲

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); 

這種處理所有可能的字符

相關問題