Java正则表达式判断数字
在Java中,可以使用正则表达式来判断一个字符串是否为数字,以下是几种常见的数字判断方法:

判断整数
public static boolean isInteger(String str) {
if (str == null || str.isEmpty()) {
return false;
}
return str.matches("-?\\d+");
}
判断正整数
public static boolean isPositiveInteger(String str) {
if (str == null || str.isEmpty()) {
return false;
}
return str.matches("\\d+");
}
判断负整数
public static boolean isNegativeInteger(String str) {
if (str == null || str.isEmpty()) {
return false;
}
return str.matches("-\\d+");
}
判断浮点数
public static boolean isDouble(String str) {
if (str == null || str.isEmpty()) {
return false;
}
return str.matches("-?\\d+(\\.\\d+)?");
}
判断科学计数法数字
public static boolean isScientificNumber(String str) {
if (str == null || str.isEmpty()) {
return false;
}
return str.matches("-?\\d+(\\.\\d+)?[eE][+-]?\\d+");
}
更全面的数字判断(包括各种数字格式)
public static boolean isNumber(String str) {
if (str == null || str.isEmpty()) {
return false;
}
// 匹配整数、浮点数、科学计数法
return str.matches("-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?");
}
使用示例
public static void main(String[] args) {
System.out.println(isInteger("123")); // true
System.out.println(isInteger("-456")); // true
System.out.println(isInteger("12.3")); // false
System.out.println(isDouble("12.3")); // true
System.out.println(isScientificNumber("1.23e-4")); // true
System.out.println(isNumber("123")); // true
System.out.println(isNumber("12.3")); // true
System.out.println(isNumber("1.23e-4")); // true
}
注意事项
- 这些方法只验证字符串格式是否为数字,不验证数值是否在合理范围内(如是否溢出)
- 对于空字符串或null输入,方法会返回false
- 如果需要验证特定范围的数字(如0-100),可以在正则表达式中添加限制
- 对于金融计算等需要高精度的场景,建议使用BigDecimal而不是浮点数
更严格的正则表达式
如果需要更严格的数字验证(如不允许前导零,除非是0本身),可以使用:
public static boolean isStrictNumber(String str) {
if (str == null || str.isEmpty()) {
return false;
}
// 匹配整数、浮点数、科学计数法,更严格的格式
return str.matches("-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?");
}
这个正则表达式会拒绝类似"0123"这样的前导零数字(除非是"0"本身)。

