温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java正则如何匹配数字

发布时间:2026-07-24 05:49:06 来源:亿速云 阅读:107 作者:小樊 栏目:编程语言

在 Java 中,正则表达式匹配数字常见有几种用法,取决于你想匹配的是“单个数字”“整数”“小数”“负数”等。下面按常见场景说明,并给出示例代码。


一、匹配单个数字(0–9)

String regex = "\\d";

或等价写法:

String regex = "[0-9]";

示例

String text = "a1b2c3";
Pattern p = Pattern.compile("\\d");
Matcher m = p.matcher(text);
while (m.find()) {
    System.out.println(m.group());
}

输出:

1
2
3

二、匹配多位整数(正整数)

String regex = "\\d+";

示例

String text = "年龄是18岁,学号是2023";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(text);
while (m.find()) {
    System.out.println(m.group());
}

输出:

18
2023

三、匹配整数(含负数)

String regex = "-?\\d+";

示例

String text = "温度-5度,明天3度";
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(text);
while (m.find()) {
    System.out.println(m.group());
}

四、匹配小数(如 3.14)

String regex = "\\d+\\.\\d+";

示例

String text = "身高1.75,体重65.5";
Pattern p = Pattern.compile("\\d+\\.\\d+");
Matcher m = p.matcher(text);
while (m.find()) {
    System.out.println(m.group());
}

五、匹配数字(整数 + 小数 + 负数)

常用通用写法:

String regex = "-?\\d+(\\.\\d+)?";

✅ 可匹配:

  • 10
  • -10
  • 3.14
  • -3.14

六、校验整个字符串是否是数字(常用)

使用 String.matches()

String num = "123.45";
boolean isNumber = num.matches("-?\\d+(\\.\\d+)?");
System.out.println(isNumber);

⚠️ 注意:
matches() 默认匹配整个字符串,不需要加 ^$


七、常见转义注意点(非常重要)

在 Java 字符串中:

正则 Java 字符串
\d "\\d"
\. "\\."
\\ "\\\\"

八、总结速查表

需求 正则
单个数字 \\d
正整数 \\d+
整数(含负) -?\\d+
小数 \\d+\\.\\d+
通用数字 -?\\d+(\\.\\d+)?

如果你有具体场景(比如:只能正数、科学计数法、金额、手机号、IP 地址等),我可以帮你写更精确的正则

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI