一、用 java 自带的函数
/**
* 判断一个 string 类型的字符串是不是一个数字
*
* @param str string 类型的字符串
* @return <code>true</code> 该 string 类型的字符串是十进制正整数. 其他的会返回<code>false</code>
*/
private static boolean judgeByToCharArray(final String str) {
// null or empty
if (str == null || str.length() == 0) {
return false;
}
return str.chars().allMatch(Character::isDigit);
}
二、使用正则表达式
/**
* 使用正则表达式判断字符串是否是数字
*
* @param str string 类型的字符串
* @return <code>true</code> 该 string 是整数. 其他的会返回<code>false</code>
*/
public static boolean isNumericByRegEx(String str) {
// ?:0或1个, *:0或多个, +:1或多个
// 匹配所有整数
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
// 匹配小数
Pattern pattern2 = Pattern.compile("^[-\\+]?[\\d]+[.][\\d]+$");
return pattern.matcher(str).matches() || pattern2.matcher(str).matches();
}
三、使用 ascii 码
/**
* 使用 ASCII 码判断字符串是否是数字
*
* @param str string 类型的字符串
* @return <code>true</code> 该 string 类型的字符串是十进制正整数. 其他的会返回<code>false</code>
*/
public static boolean isNumericByAscii(String str) {
if (str == null || str.length() == 0) {
return false;
}
return str.chars().allMatch(chr -> (chr >= 48 && chr <= 57));
}
四、parse 方法
/**
* 判断一个 string 类型的字符串是不是一个数字
*
* @param str string 类型的字符串
* @return <code>true</code> 该 string 类型的字符串是十进制正整数. 其他的会返回<code>false</code>
*/
public static boolean isNumeric(final String str) {
// null or empty
if (str == null || str.length() == 0) {
return false;
}
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException ex) {
try {
Float.parseFloat(str);
return true;
} catch (NumberFormatException exx) {
return false;
}
}
}
}
五、第三方类库
/**
* 判断一个 string 类型的字符串是不是一个数字
*
* <p>
* commons-lang3 库 -- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
* </p>
*
* @param str string 类型的字符串
* @return <code>true</code> 该 string 类型的字符串是数字
*/
private static boolean judgeByCommonsLong3(final String str) {
// NumberUtils.isParsable(str)
// NumberUtils.isDigits(str)
// 这一个效果好一点
return NumberUtils.isCreatable(str);
}
还没有评论,来说两句吧...