java判断字符串是否为数字的方法是什么

1230
2023/5/6 16:06:10
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Java 判断字符串是否为数字的方法有以下几种:

1、使用正则表达式

可以使用正则表达式判断字符串是否为数字。例如,使用 \d+ 匹配一个或多个数字,示例代码如下:

public static boolean isNumeric(String str) {

return str.matches("\\d+");

}

2、使用 NumberUtils.isNumber() 方法

可以使用 Apache Commons Lang 库中的 NumberUtils.isNumber() 方法判断字符串是否为数字。该方法会自动将字符串转换为数字类型,如果转换成功,则说明字符串为数字。示例代码如下:

import org.apache.commons.lang3.math.NumberUtils;


public static boolean isNumeric(String str) {

return NumberUtils.isNumber(str);

}

3、使用 Double.parseDouble() 方法

可以使用 Double.parseDouble() 方法将字符串转换为 double 类型,如果转换成功,则说明字符串为数字。示例代码如下:

public static boolean isNumeric(String str) {

try {

Double.parseDouble(str);

return true;

} catch (NumberFormatException e) {

return false;

}

}

需要注意的是,以上方法只能判断是否为整数或小数,如果需要判断更复杂的数字格式,需要使用更复杂的正则表达式或自定义的方法。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java中的properties怎么调用