原文: https://www.programiz.com/java-programming/examples/check-string-numeric
public class Numeric {
public static void main(String[] args) {
String string = "12345.15";
boolean numeric = true;
try {
Double num = Double.parseDouble(string);
} catch (NumberFormatException e) {
numeric = false;
}
if(numeric)
System.out.println(string + " is a number");
else
System.out.println(string + " is not a number");
}
}运行该程序时,输出为:
12345.15 is a number在上面的程序中,我们有一个名为string的String,其中包含要检查的字符串。 我们还有一个布尔值number,它存储最终结果是否为数字。
要检查string是否仅包含数字,在try块中,我们使用Double的parseDouble()方法将字符串转换为Double。
如果抛出错误(即NumberFormatException错误),则表示string不是数字,并且number设置为false。 否则,这是一个数字。
但是,如果要检查是否有多个字符串,则需要将其更改为函数。 而且,逻辑基于抛出异常,这可能会非常昂贵。
相反,我们可以使用正则表达式的功能来检查字符串是否为数字,如下所示。
public class Numeric {
public static void main(String[] args) {
String string = "-1234.15";
boolean numeric = true;
numeric = string.matches("-?\\d+(\\.\\d+)?");
if(numeric)
System.out.println(string + " is a number");
else
System.out.println(string + " is not a number");
}
}运行该程序时,输出为:
-1234.15 is a number在上面的程序中,我们使用正则表达式来检查string是否为数字,而不是使用try-catch块。 这是使用String的matches()方法完成的。
在matches()方法中,
-?允许零或多个-用于字符串中的负数。\\d+检查字符串必须至少包含 1 个或多个数字(\\d)。(\\.\\d+)?允许零个或多个给定模式(\\.\\d+),其中\\.检查字符串是否包含.(小数点)- 如果是,则应至少跟一个或多个数字
\\d+。