2010年1月27日 星期三

Java String replaceAll 真的很 tricky

String start = "yours now for just <amount>";
String price = "12$9.99";
// 必須取代 $ 成為 \$,別懷疑就是六個 backslash!!!

price = price.replaceAll("\\$", "\\\\\\$");
String end = start.replaceAll("<amount>", price);


replaceAll 第一個參數要小心特殊符號,大家都知道...
而且,它的第二個參數,不能包含 $,否則會出現
java.lang.StringIndexOutOfBoundsException
是因為 "$數字",會被當成 regex 在 replace 用的 "變數" (ex. $&, $1, $2...)
若 $ 不是變數,就要用 backslash 去 escape $
或是用 $$ 來跳脫 $ (把所有的 $ 取代成兩個 $$)
 

沒有留言:

張貼留言