Java判断字符串能否转为数字

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
自我控制是最强者的本能-萧伯纳
原文地址:https://www.cnblogs.com/CF1314/p/13879904.html