Java Double 正则表达式
在 Java 中,可以使用正则表达式来验证或匹配 double 类型的数值,以下是一些常用的正则表达式模式:

基本正则表达式模式
简单的 double 匹配(可选符号 + 整数部分 + 小数点 + 小数部分)
String doubleRegex = "[-+]?[0-9]*\\.?[0-9]+";
更严格的 double 匹配(必须有数字在点前后)
String strictDoubleRegex = "[-+]?[0-9]+(\\.[0-9]+)?";
允许科学计数法的 double
String scientificDoubleRegex = "[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?";
完整示例代码
import java.util.regex.Pattern;
public class DoubleRegexExample {
public static void main(String[] args) {
// 基本double正则表达式
String doubleRegex = "[-+]?[0-9]*\\.?[0-9]+";
Pattern doublePattern = Pattern.compile(doubleRegex);
// 测试用例
String[] testCases = {
"123.45", "-123.45", "+123.45",
"123", ".45", "123.",
"1.23e4", "1.23E-4", "123.45e67",
"abc", "123..45", ""
};
System.out.println("基本double正则表达式测试:");
for (String testCase : testCases) {
System.out.printf("%-10s -> %b%n", testCase,
doublePattern.matcher(testCase).matches());
}
// 更严格的double正则表达式
String strictDoubleRegex = "[-+]?[0-9]+(\\.[0-9]+)?";
Pattern strictDoublePattern = Pattern.compile(strictDoubleRegex);
System.out.println("\n严格double正则表达式测试:");
for (String testCase : testCases) {
System.out.printf("%-10s -> %b%n", testCase,
strictDoublePattern.matcher(testCase).matches());
}
// 科学计数法double正则表达式
String scientificDoubleRegex = "[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?";
Pattern scientificDoublePattern = Pattern.compile(scientificDoubleRegex);
System.out.println("\n科学计数法double正则表达式测试:");
for (String testCase : testCases) {
System.out.printf("%-10s -> %b%n", testCase,
scientificDoublePattern.matcher(testCase).matches());
}
}
}
更精确的 Double 正则表达式
如果需要更精确地匹配 Java 的 double 范围(包括最大值和最小值),可以使用以下正则表达式:
String preciseDoubleRegex =
"[-+]?(" +
"(0|[1-9]\\d*)(\\.\\d*)?|" + // 常规数字
"\\.\\d+" + // 只有小数部分
")([eE][-+]?\\d+)?"; // 可选的科学计数法
注意事项
-
正则表达式验证的是字符串格式,而不是数值范围,Java 的 double 有特定的数值范围(约 ±1.7976931348623157E308),正则表达式本身不检查这些范围。
-
如果需要验证数值是否在 double 范围内,应该在正则表达式验证后,尝试将其转换为 double 并捕获可能的异常。
-
对于金融或需要高精度的计算,建议使用
BigDecimal而不是 double。
(图片来源网络,侵删) -
正则表达式中的 需要转义为
\\.,因为在正则表达式中 是特殊字符。
希望这些信息对你有帮助!

