校验数字的三种方式
判断数字的三种方式
方式一:使用Character.isDigit
public static boolean isNumeric(String str){
if(str == null){
return false;
}
for (int i = str.length();--i>=0;){
if (!Character.isDigit(str.charAt(i))){
return false;
}
}
return true;
}
方式二:(不推荐使用)
public static boolean isValidInt(String value) {
try {
Integer.parseInt(value);
} catch (NumberFormatException e) {
return false;
}
return true;
}
/**
* @param if the value is between -9223372036854775808 and
* 9223372036854775807, then return true
* @return
*/
public static boolean isValidLong(String value) {
try {
Long.parseLong(value);
} catch (NumberFormatException e) {
return false;
}
return true;
}
方式三:通过正则表达式(推荐使用)
/***
* 判断 String 是否是 int<br>通过正则表达式判断
*
* @param input
* @return
*/
public static boolean isInteger(String input){
Matcher mer = Pattern.compile("^[+-]?[0-9]+$").matcher(input);
return mer.find();
}
public static boolean isDouble(String input){
Matcher mer = Pattern.compile("^[+-]?[0-9.]+$").matcher(input);
return mer.find();
}