示例 1:检查字符串是否为数字
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
,其中包含要检查的字符串。我们还有一个布尔值 numeric,用于存储最终结果是否为数字。
要检查 string 是否只包含数字,在 try 块中,我们使用 Double
的 parseDouble()
方法将字符串转换为 Double
。
如果它抛出错误(即 NumberFormatException
错误),则意味着 string 不是数字,并且 numeric 被设置为 false
。否则,它就是数字。
但是,如果要检查多个字符串,则需要将其更改为函数。而且,基于抛出异常的逻辑,这可能非常昂贵。
相反,我们可以利用正则表达式的强大功能来检查字符串是否为数字,如下所示。
示例 2:使用正则表达式 (regex) 检查字符串是否为数字
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
在上面的程序中,我们没有使用 try-catch 块,而是使用 regex 来检查 string 是否为数字。这是通过 String 的 matches() 方法完成的。
在 matches()
方法中,
-?
允许字符串中出现零个或多个-
(负数)。\\d+
检查字符串必须包含至少一个或多个数字 (\\d
)。(\\.\\d+)?
允许出现零个或多个给定的模式(\\.\\d+)
,其中\\.
检查字符串是否包含.
(小数点)。- 如果是,则后面应跟至少一个或多个数字
\\d+
。