字體:小 中 大 | |
|
|
2010/07/23 18:18:23瀏覽650|回應0|推薦2 | |
字串處理中有個常用到的 Method 叫做 replaceAll() r 系列,除 replace() 外, 如 , replaceAll(), replaceFirst() 等家族被用來取代字串用 public String replaceAll(char oldChar, char newChar) 其輸入的參數並不單純只是個字串,而是一個 patterm,一個正則表達式 故 常會發生一種情況! Example: 現在,我們目的是要把 "abc(def)" 字串去掉 "(def)" 剩下 "abc",所以寫了下面這段 code String str = "abc(def)"; str = str.replaceAll( "(def)", "" ); 這兩行 code 執行完,str 會變成 "abc()" 而不是我們要的 "abc" 原因就是因為 replace() 的輸入參數是屬於一段正則表達式 而 () 似乎是在不知哪方面屬於特殊字元 故 正確的 code 應改為 String str = "abc(def)"; str = str.replaceAll( "\\(def\\)", "" ); |
|
( 知識學習|語言 ) |