記錄緣由:
公司項目需要從xml中獲取標識為NUMBER的字符串,將之存入數據庫中,存入的列的類型即為NUMBER。當遇到非數字時,原實現是通過異常:
String plainValue = null;
try { plainValue = new BigDecimal(colValue).toPlainString(); } catch (Exception e) { plainValue = ""; }
沒有去研究過BigDecimal(String)這個構造方法的內部實現,得空去研究一下。只是覺得無必要還是盡量不利用異常去做邏輯處理,所以這里用正則表達式實現:
private static final String NUMBER_REGEX = "([0-9]\\d*\\.?\\d*)|((-)?[0-9]\\d*\\.?\\d*)"; public static boolean matcher(String value) { Matcher matcher = pattern.matcher(value); return matcher.matches(); } public String getTransferValue(String colValue){
String plainValue = matcher(colValue) ? colValue : ""; return plainValue; }
以上。小白一個,歡迎指正!