public static boolean isNumeric(String str) {
if (str == null || str.isEmpty()) return false;
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
// 僅整數 (非負)
public static boolean isInteger(String str) {
return str != null && str.matches("\\d+");
}
// 整數 (含正負號)
public static boolean isIntegerWithSign(String str) {
return str != null && str.matches("[+-]?\\d+");
}
// 浮點數 (含科學計數法)
public static boolean isNumericRegex(String str) {
return str != null && str.matches("[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?");
}
public static boolean isNumericAscii(String str) {
if (str == null || str.isEmpty()) return false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') return false; // '0'=48, '9'=57
}
return true;
}
public static boolean isNumericStream(String str) {
return str != null && !str.isEmpty() &&
str.chars().allMatch(Character::isDigit);
}
// Apache Commons Lang 3
StringUtils.isNumeric(str); // 僅數字
StringUtils.isNumericSpace(str); // 數字或空白
NumberUtils.isCreatable(str); // 可解析為數字 (含負號、小數、科學計數法)
// Guava
CharMatcher.DIGIT.matchesAllOf(str);
public static boolean isNumericParse(String str) {
if (str == null) return false;
try {
Long.parseLong(str); // 或 Double.parseDouble
return true;
} catch (NumberFormatException e) {
return false;
}
}
| 方法 | 吞吐量 (ops/ms) | 相對性能 | 適用場景 |
|---|---|---|---|
| ASCII 範圍 | ~15,000 | 基準 1.0x | 純 ASCII 數字、極高頻調用 |
| Character.isDigit | ~12,000 | 0.8x | 通用 Unicode 數字檢查 |
| 預編譯 Pattern | ~8,000 | 0.5x | 複雜格式驗證 (小數、科學計數法) |
| String.matches | ~3,000 | 0.2x | 低頻、臨時驗證 |
| NumberUtils.isCreatable | ~2,500 | 0.17x | 通用數字解析驗證 |
| 異常捕獲法 | ~200 | 0.01x | 極少數邊界情況 |
需要驗證格式? ├─ 僅非負整數 → ASCII 範圍 或 Character.isDigit ├─ 整數(含符號) → 預編譯 Pattern: [+-]?\\d+ ├─ 浮點數/科學計數法 → NumberUtils.isCreatable() 或預編譯完整正則 └─ 通用數字解析 → NumberUtils.isCreatable() (推薦生產環境)
public final class NumericUtils {
private static final Pattern INTEGER_PATTERN = Pattern.compile("[+-]?\\d+");
private static final Pattern DECIMAL_PATTERN = Pattern.compile("[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?");
private NumericUtils() {}
public static boolean isPositiveInteger(String str) {
return str != null && !str.isEmpty() &&
str.chars().allMatch(Character::isDigit);
}
public static boolean isInteger(String str) {
return str != null && INTEGER_PATTERN.matcher(str).matches();
}
public static boolean isDecimal(String str) {
return str != null && DECIMAL_PATTERN.matcher(str).matches();
}
public static boolean isParsableNumber(String str) {
return NumberUtils.isCreatable(str); // 需 commons-lang3 依賴
}
}
根據業務場景選擇合適方法:高頻簡單判斷用 ASCII/Character,複雜格式用預編譯正則,生產通用驗證首選成熟工具庫。