Java判断字符串是否是数字
使用正则表达式
javapublic class NumericCheck { private static final Pattern NUMBER_PATTERN = Pattern.compile("-?\\d+(\\.\\d+)?"); public static boolean isNumeric(String str) { return str != null && NUMBER_PATTERN.matcher(str).matches(); } public static void main(String[] args) { System.out.println(isNumeric("123")); // true System.out.println(isNumeric("-123.45")); // true System.out.println(isNumeric("abc")); // false } }通过 Double.parseDouble 或 Integer.parseInt 转换字符串,捕获异常来判断
javapublic class NumericCheck { public static boolean isNumeric(String str) { try { Double.parseDouble(str); return true; } catch (NumberFormatException e) { return false; } } public static void main(String[] args) { System.out.println(isNumeric("123")); // true System.out.println(isNumeric("12.34")); // true System.out.println(isNumeric("abc")); // false } }逐字符检查字符串是否仅包含数字字符(仅适用于整数)
javapublic class NumericCheck { public static boolean isNumeric(String str) { if (str == null || str.isEmpty()) return false; for (char c : str.toCharArray()) { if (!Character.isDigit(c)) return false; } return true; } public static void main(String[] args) { System.out.println(isNumeric("123")); // true System.out.println(isNumeric("12a3")); // false } }使用 Apache Commons Lang
xml<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency>javaimport org.apache.commons.lang3.math.NumberUtils; public class NumericCheck { public static void main(String[] args) { System.out.println(NumberUtils.isCreatable("123")); // true System.out.println(NumberUtils.isCreatable("-12.34")); // true System.out.println(NumberUtils.isCreatable("0xFF")); // true System.out.println(NumberUtils.isCreatable("abc")); // false } }