Java判斷字符串能否轉為數字
在上篇博客中介紹了字符串與數字相互轉換的方法,在轉換前通常需要加上判斷,避免可能拋出的異常。
1、使用正則表達式
通過使用 String 的 matches() 方法進行正則表達式的判斷,可以簡便地判斷出來。
數字又分為整數和小數,所以需要進行兩遍正則表達式的判斷。
String s1 = "-123";
String s2 = "123.345";
//是否為整數
if (s1.replace("-", "").matches("^[0-9]+$")) {
System.out.println("s1:" + true);
}else {
System.out.println("s1:" + false);
}
//是否為小數
if(s2.replace("-", "").matches("\\d+.\\d+")) {
System.out.println("s2:" + true);
}else {
System.out.println("s2:" + false);
}
輸入結果如下:
s1:true
s2:true
2、StringUtils.isNumeric() 方法
這是一個字符串的工具類,isNumeric() 可以判斷 字符串是否為數字字符串,即只能判斷純數字字符串,不推薦使用。
if (StringUtils.isNumeric(s1)) {
System.out.println("ss1:" + true);
}
輸出結果如下:
ss1:true