注意使用正則表達式和普通字符串的區別:
昨天發現一個因為誤用正則表達式而導致的bug,
錯誤代碼:
這段代碼的本意是為了將mountPoint中的所有?替換成為|,但是由于沒有仔細看replaceAll的參數說明,導致了兩個參數都是用regular express所必需的\\轉義符號。
因此正確的代碼是:
同樣需要注意的包括indexOf,split
昨天發現一個因為誤用正則表達式而導致的bug,
錯誤代碼:
public String get××××() {
if(mountPoint!=null && mountPoint.length()>0){
return mountPoint.replaceAll("\\?", "\\|");
}else
return "";
}
if(mountPoint!=null && mountPoint.length()>0){
return mountPoint.replaceAll("\\?", "\\|");
}else
return "";
}
這段代碼的本意是為了將mountPoint中的所有?替換成為|,但是由于沒有仔細看replaceAll的參數說明,導致了兩個參數都是用regular express所必需的\\轉義符號。
replaceAll(String regex, String replacement)
因此正確的代碼是:
public String get××××() {
if(mountPoint!=null && mountPoint.length()>0){
return mountPoint.replaceAll("\\?", "|");
}else
return "";
}
if(mountPoint!=null && mountPoint.length()>0){
return mountPoint.replaceAll("\\?", "|");
}else
return "";
}
同樣需要注意的包括indexOf,split