很多时候,在处理字符串的时候,需要检查给定的字符串是否是数字、或者整数等。
下面整理下判断数字或者整数的方式
Java原生方法
Java的最普通的判断数字、小数的方法,就是用
Integer.parseInt(string);
Double.parseDouble(string);
去解析,如果能解析出Integer或者Double,不抛出异常,那么说明这个string是数字或者小数,这种方式虽然有点不优雅,但是有效!
不过应该是不推荐使用异常来判断的,后面还会介绍使用正则表达式来判断
public static void main(String[] args) {
System.out.println(isNumber("012345"));
System.out.println(isDecimal("-012345.12345667"));
}
/**
* 利用Integer.parseInt判断给定文本是否是纯数字组成
*/
public static boolean isNumber(String string) {
if (isEmpty(string))
return false;
try {
Integer.parseInt(string);
} catch (NumberFormatException e) {
return false;
}
return true;
}
/**
* 利用Double.parseDouble判断给定文本是否是数字(可以是负数、小数)
*/
public static boolean isDecimal(String string) {
if (isEmpty(string))
return false;
try {
Double.parseDouble(string);
} catch (NumberFormatException e) {
return false;
}
return true;
}
public static boolean isEmpty(String string) {
if(string == null) {
return true;
}
return string.trim().length() == 0;
}
利用正则表达式检查文本是否符合数字或者小数的格式
/**
* 利用正则判断给定文本是否是纯数字组成
*/
public static boolean isNumber(String numberString) {
if (isEmpty(numberString))
return false;
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(numberString);
return m.matches();
}
public static boolean isEmpty(String string) {
if(string == null) {
return true;
}
return string.trim().length() == 0;
}
/**
* 利用正则判断给定文本是否是数字(可以是负数、小数)
*/
public static boolean isDecimal(String string) {
if (isEmpty(string))
return false;
// Pattern p = Pattern.compile("-?\\d+(\\.\\d+)?");
Pattern p = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
Matcher m = p.matcher(string);
return m.matches();
}
org.apache.commons.lang.StringUtils.isNumeric无法判断小数或者负数
看到网上说org.apache.commons.lang的StringUtils.isNumeric可以判断,虽然是比较有名的工具包,但是发现并不能很好的判断,反例如下:
// -12345和-12345.678返回false,说明不能判断小数或者负数
System.out.println(org.apache.commons.lang3.StringUtils.isNumeric("-12345.678"));
System.out.println(org.apache.commons.lang3.StringUtils.isNumeric("-12345"));
Javascript下判断文本是否是数字,详见我之前的博客:https://blog.terrynow.com/2021/01/28/javascript-tool-check-string-is-number-or-float/
文章评论
Kpfxlk buy cialis pills parecido a la viagra buy cialis canada pharmacy Supreme Suppliersmumbaiindia Cialis Cialis Generique Comparer Prix