一、使用正則表達式
public static boolean isNumeric(String str) { if (str == null || str.length() == 0) { return false; } return str.matches("-?[0-9]+.?[0-9]*"); }
正則表達式可以檢測字元串是否為數字類型,其中「-?」表示可選的負號,”[0-9]+”表示一串數字,”.?[0-9]*”表示可選的小數部分。
二、使用Java內置函數
public static boolean isNumeric(String str) { if (str == null || str.length() == 0) { return false; } try { Double.parseDouble(str); return true; } catch (NumberFormatException e) { return false; } }
使用Java內置函數Double.parseDouble()可以直接將字元串轉成Double類型,如果轉換成功則說明字元串為數字類型,否則會拋出NumberFormatException錯誤。
三、使用Apache Commons Lang庫
public static boolean isNumeric(String str) { if (str == null || str.length() == 0) { return false; } return NumberUtils.isNumber(str); }
Apache Commons Lang庫提供了NumberUtils.isNumber()方法,可以判斷字元串是否為數字類型。
四、使用正整數/負整數/小數判斷
public static boolean isPositiveInteger(String str) { if (str == null || str.length() == 0) { return false; } Pattern pattern = Pattern.compile("[0-9]*"); Matcher isPositiveInteger = pattern.matcher(str); return isPositiveInteger.matches(); } public static boolean isNegativeInteger(String str) { if (str == null || str.length() == 0) { return false; } Pattern pattern = Pattern.compile("^-[0-9]*$"); Matcher isNegativeInteger = pattern.matcher(str); return isNegativeInteger.matches(); } public static boolean isDecimal(String str){ if(str == null || str.length() == 0){ return false; } Pattern pattern = Pattern.compile("^[-+]?[0-9]+(\\.[0-9]+)?$"); Matcher matcher = pattern.matcher(str); return matcher.matches(); }
根據需要判斷字元串是否正整數/負整數/小數類型,使用正則表達式可以輕鬆實現。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/180269.html