2017-06-03 46 views
1

我有這樣的方法,它的作品一樣打算:replaceAll()只工作一次,但不是兩次?

public void splitReplaceAndPrint() 
{ 
    words = new String[200]; 

    String bookReplacedWithNoCommas = book.replaceAll(",", ""); 

    words = bookReplacedWithNoCommas.split(" "); 

    for(int i = 0; i < words.length; i++) 
    { 
     System.out.println(words[i]); 
    } 
} 

但是,如果我嘗試藏漢刪除點,這樣的...:

public void splitReplaceAndPrint() 
{ 
    words = new String[200]; 

    String bookReplacedWithNoCommas = book.replaceAll(",", ""); 
    String bookReplacedWithNoPoints = bookReplacedWithNoCommas.replaceAll(".", ""); 

    words = bookReplacedWithNoPoints.split(" "); 

    for(int i = 0; i < words.length; i++) 
    { 
     System.out.println(words[i]); 
    } 
} 

...沒有被打印出來。爲什麼這不起作用?

+0

他你檢查究竟包含在'bookReplacedWithNoPoints '? – Carcigenicate

+0

您的圖書變量的價值是什麼? – TmTron

+0

@Carcigenicate是的,它是空的。但我不明白爲什麼。 – CHBR

回答

7

因爲.意味着什麼,所以逃避它。

在正則表達式.將匹配任何字符,因此將在字符串替換一切如此簡單,你應該採取的,而不是昂貴的正則表達式的replace優勢

book.replace(",", ""); 

或 刪除這兩個,.單步

book.replaceAll("[.,]", ""); 

[.,][]表示一個character class,它們表示匹配逗號和d OT


以防萬一,如果你想使用replace刪除單個單個字符那麼你可以申請replace功能的鏈

String book ="The .bo..ok of ,eli.."; 
book.replace(",","").replace(".",""); // The book of eli 
+1

或者,只需使用['replace'](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replace-char-char-)而不是'replaceAll '? –

+0

明白了,謝謝! :D – CHBR

+0

@tobias_k等待好友寫作需要時間 –

3

您需要轉義點,否則它將匹配任何字符。這種轉義是必要的,因爲replaceAll將第一個參數視爲正則表達式。第一個參數,以你的情況replaceAll\\..

String bookReplacedWithNoPoints = bookReplacedWithNoCommas.replaceAll("\\.", ""); 
+0

考慮爲解決問題添加解釋。 –

+0

阿哈,今天學到了一些新東西。非常感謝! – CHBR

+0

replaceAll()以正則表達式作爲輸入和「。」是正則表達式中的一個特殊字符。 –